• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
fir

code -> .data & data -> .code

22 posts in this topic

I heard that sometimes (often?) compilers put the data to code section

and vice versa (code to data section) though it is generally not good

and 'can even degrade performance'  - but why they do that was not explained

 

does maybe someone know something about that?

Edited by fir
-3

Share this post


Link to post
Share on other sites

I'm not super knowledgeable in this area, perhaps someone can illuminate me -- aren't the code and data sections mostly throwbacks to the 16bit segmented memory days?

 

I recall that when I learned to program in a compilable version of QuickBASIC (v4.5 for those who remember) they actually had instructions for setting the code and data segments that were active. One of the major optimizations I discovered in one of my programs once, was that the structure of my map rendering was causing me to jump all over memory and even across data segments -- which was obviously horrible. When I fixed it, I went from 5fps to 50fps, in a tight rendering loop where blitting should have been the bottleneck.

1

Share this post


Link to post
Share on other sites

Other than hearing this, have you also read it somewhere on the interwebs? Perhaps you can post a link to such a claim, so we can know exactly what you are talking about?

alright, the first source is in agner fog objconv instruction

 

"11.27 How does the disassembler distinguish between code and data?
The first assumption is that code segments contain code and data segments contain data.
Unfortunately, some compilers put jump tables and other data into the code segment, even
though this gives inferior performance."
 
the second
 
"The problem wouldn't be as difficult if data were limited to the .data section (segment) of an executable (explained in a later chapter) and if executable code were limited to the .code section of an executable, but this is often not the case. Data may be inserted directly into the code section (e.g. jump address tables, constant strings), and executable code may be stored in the data section (although new systems are working to prevent this for security reasons)."
 
from
 
but this is not further explained and i wonder what is a reason of 
this "violations"
0

Share this post


Link to post
Share on other sites

You can really put anything you want in sections of the executable, it's all just bytes anyway. The sections can be called anything also. The only difference is the flags that the OS uses to allocate the memory. Pure data sections could for example be allocated as non-executable or read-only.

This is the function that Windows uses to allocate memory when it loads executables, it might give you some hints about this.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa366887(v=vs.85).aspx

I'm not sure what he's on about when he says that data in the code section could give you performance issues. The data needs to be somewhere, and I don't see why loading it from one arbitrary memory address would be worse than doing it from another arbitrary address. It might even be beneficial to have it near the code, because the jump table data would likely end up in the same memory page as the code that uses it... But I'm not sure, so don't qote me on that. But the compiler writers are usually not morons, so it would be pretty safe to bet that they know what they are doing.

 

not always sometimes compilers do a really weak stuff...

i also sont know what he mean about this performance issues,

though i must say that year ot two years ago i was calling the data - i mean i wrote the procedures right in machine code in my prog like

 

char asmDot_SSE[] =
{
 
 0xC8, 0x00, 0x00, 0x00,
 0x8B, 0x45, 0x08,
 0x8B, 0x5D, 0x0C,
 0x8B, 0x4D, 0x10,
 0x0F, 0x10, 0x00,
 0x0F, 0x10, 0x0B,
 0x0F, 0x59, 0xC1,
 0x0F, 0x12, 0xC8,
 0x0F, 0x58, 0xC8,
 0x0F, 0x28, 0xC1,
 0x0F, 0xC6, 0xC9, 0x01,
 0xF3, 0x0F, 0x58, 0xC1,
 0xF3, 0x0F, 0x11, 0x01,
 0xC9,
 0xC3
 
};
 
and when counting the execution times it was much slower than 
executing it in normal code section - i dont know what was a reason of that but it worked but had a speed penalty sadly
 
mayve some guarding mechanism is involved ? maybe it works also in opossite way, i mean accessing data from .code pages.. dont know
Edited by fir
0

Share this post


Link to post
Share on other sites

I'm not super knowledgeable in this area, perhaps someone can illuminate me -- aren't the code and data sections mostly throwbacks to the 16bit segmented memory days?

 

I recall that when I learned to program in a compilable version of QuickBASIC (v4.5 for those who remember) they actually had instructions for setting the code and data segments that were active. One of the major optimizations I discovered in one of my programs once, was that the structure of my map rendering was causing me to jump all over memory and even across data segments -- which was obviously horrible. When I fixed it, I went from 5fps to 50fps, in a tight rendering loop where blitting should have been the bottleneck.

 

no, you mixing old 640K ds: cs: stuff here... 

i am moving about .data and .code sections in program image,

which are later mapped into a ram memory where ram pages are also mapped as "executable" "data" "readolny data" etc - and i wonder on the details of this here

0

Share this post


Link to post
Share on other sites

and when counting the execution times it was much slower than 
executing it in normal code section - i dont know what was a reason of that but it worked but had a speed penalty sadly


I'm willing to bet you'd see a lot of overhead in the function that calls into your code array; jumps and address dereferences and so on. There's also a difference between the data L1 cache and the code L1 cache, and pulling data in to be executed likely incurs additional cache misses and requests in order to run. This is also a possible reason for data in the code section being slower. One would have to look at the disassembly and run under a suitably capable profiler (vtune, cachegrind, etc.) to verify that assumption. This is part of what locality of reference in code is all about and why a profile-guided linker will lay out the compiled code differently (so functions that call each other end up close together in the machine code image). Naively written SSE code can also incur a lot of overhead due to various modes and flags; compiler intrinsics are almost always the right way to go to avoid these kinds of issues thanks to the compiler being able to set things up properly when you're not hiding your use of SSE from the compiler.

In any case, this works on Windows because you have to opt in to the NX bit on Windows for backwards-compatibility reasons. It's usually on by default in Linux and most other major OSes that support the feature. The flag is set on by default with newer versions of Visual Studio, I think, but imported project files or projects built with older VS versions probably don't have the bit set in the executable image to enable the NX behavior. This is similar to how a 32-bit application has to opt in to being LAA (large address aware) to access more than 2GB of memory even on a 64-bit kernel.
1

Share this post


Link to post
Share on other sites
Jump tables for switch statements are technically data which are typically stored in the code section after the end of the function which contains the switch statement.
 
Microsoft compilers output files organized like so:
 
 
Headers
Code Section (the headers designate this section as Execute+Read)
    Function 0
        Instructions
        Optional: NOP or INT3 padding
        Optional: Case mapping table (and optional padding to the next pointer-sized boundary)
        Optional: Case block pointers (and optional padding to the next 16 byte boundary)
    Function 1
        Instructions
        ...ETC...
Initialized Data Section(s) (the headers designate these section(s) as Read+Write or just Read)
    Data!
Import Section (readonly after the loader finishes with it)
    Data!
Export Section (readonly after the loader finishes with it)
    Data!
Relocation Section (discarded after the loader finishes with it)
    Data!
Resource Section (readonly)
    Data!
(etc...)
Other compilers (or binary compressors such as UPX) are free to rearrange anything besides the main header that they want to. Edited by Nypyren
1

Share this post


Link to post
Share on other sites

Jump tables for switch statements are technically data which are typically stored in the code section after the end of the function which contains the switch statement.
 
Microsoft compilers output files organized like so:
 
 

Headers
Code Section (the headers designate this section as Execute+Read)
    Function 0
        Instructions
        Optional: NOP or INT3 padding
        Optional: Case mapping table (and optional padding to the next pointer-sized boundary)
        Optional: Case block pointers (and optional padding to the next 16 byte boundary)
    Function 1
        Instructions
        ...ETC...
Initialized Data Section(s) (the headers designate these section(s) as Read+Write or just Read)
    Data!
Import Section (readonly after the loader finishes with it)
    Data!
Export Section (readonly after the loader finishes with it)
    Data!
Relocation Section (discarded after the loader finishes with it)
    Data!
Resource Section (readonly)
    Data!
(etc...)
Other compilers (or binary compressors such as UPX) are free to rearrange anything besides the main header that they want to.

 

 

but why they do that? case values table and also pointers table i think is data do maybe it would be better if it would be in .data

0

Share this post


Link to post
Share on other sites

 

and when counting the execution times it was much slower than 
executing it in normal code section - i dont know what was a reason of that but it worked but had a speed penalty sadly


I'm willing to bet you'd see a lot of overhead in the function that calls into your code array; jumps and address dereferences and so on. There's also a difference between the data L1 cache and the code L1 cache, and pulling data in to be executed likely incurs additional cache misses and requests in order to run. This is also a possible reason for data in the code section being slower. One would have to look at the disassembly and run under a suitably capable profiler (vtune, cachegrind, etc.) to verify that assumption. This is part of what locality of reference in code is all about and why a profile-guided linker will lay out the compiled code differently (so functions that call each other end up close together in the machine code image). Naively written SSE code can also incur a lot of overhead due to various modes and flags; compiler intrinsics are almost always the right way to go to avoid these kinds of issues thanks to the compiler being able to set things up properly when you're not hiding your use of SSE from the compiler.

In any case, this works on Windows because you have to opt in to the NX bit on Windows for backwards-compatibility reasons. It's usually on by default in Linux and most other major OSes that support the feature. The flag is set on by default with newer versions of Visual Studio, I think, but imported project files or projects built with older VS versions probably don't have the bit set in the executable image to enable the NX behavior. This is similar to how a 32-bit application has to opt in to being LAA (large address aware) to access more than 2GB of memory even on a 64-bit kernel.

 

 

 

i can give more info from my notes, i was tested a loops

of 1000x with rdtsc and testet such codes (down from my notes)

 

1)

    vector.x = 1.0;       //2 cycles

2)

     data_foo();  //calling a pointer to such machine code array

                // where only "ret" was contained 

                  //12 cycles

 

3)
    vector.x = 1.0; 
    data_foo();

                     //mixing one with the second

                    // few hundred cycles - with unknown reason

0

Share this post


Link to post
Share on other sites

but why they do that? case values table and also pointers table i think is data do maybe it would be better if it would be in .data


The only thing I can think of is that the processor may be able to opportunistically cache jump tables if they're located after the function, but I haven't read the cache section of the Intel documentation to know whether this is done or not. I focus more on reverse engineering than optimization, so cache behavior isn't something I know very well.
0

Share this post


Link to post
Share on other sites

 

but why they do that? case values table and also pointers table i think is data do maybe it would be better if it would be in .data


The only thing I can think of is that the processor may be able to opportunistically cache jump tables if they're located after the function, but I haven't read the cache section of the Intel documentation to know whether this is done or not. I focus more on reverse engineering than optimization, so cache behavior isn't something I know very well.

 

agner fog mentioned that this mixing compilers do (may) degrade performance (though he not gave a details)

[I am recently interested in disasembly so im searching for claryfy in such topics, will be studying coff a little soon]

0

Share this post


Link to post
Share on other sites
In principle, putting intermixing constant data in your code section could benefit from cache locality. Less so with a split L1 cache. But it can be difficult to determine when such an optimization is worthwhile.
0

Share this post


Link to post
Share on other sites

In principle, putting intermixing constant data in your code section could benefit from cache locality. Less so with a split L1 cache. But it can be difficult to determine when such an optimization is worthwhile.

 

OK, but I think it maybe is not sufficient to explain a strange few hundred cycles slowdown i noticed in above test - so maybe some other slowdown mechanizm is involved (when calling 

a code contained in the data section) - maybe i will be able to test and measure more things with hand assembly test but i coul ddo it later

0

Share this post


Link to post
Share on other sites
Few hundred cycles? that's like a L3 cache miss. That's totally in keeping with the fact that jumping to an arbitrary code block is likely to be far in memory from the previous execution.
0

Share this post


Link to post
Share on other sites

i can give more info from my notes, i was tested a loops
of 1000x with rdtsc and testet such codes (down from my notes)
 
1)
    vector.x = 1.0;       //2 cycles[/size]

2)
     data_foo();  //calling a pointer to such machine code array
                // where only "ret" was contained 
                  //12 cycles[/size]
 
3)
    vector.x = 1.0; [/size]
    data_foo();
                     //mixing one with the second
                    // few hundred cycles - with unknown reason



Without knowing what the entirety of your program looks like, we can only speculate what you might be seeing. If you post the full program's disassembly (including the address of each function) we might be able to narrow down the issue more easily.

Everything matters. If 'vector' is a stack-allocated variable or a heap variable, that matters. The address of each function. All of the rest of the code that you've omitted also matters.
0

Share this post


Link to post
Share on other sites

 

i can give more info from my notes, i was tested a loops
of 1000x with rdtsc and testet such codes (down from my notes)
 
1)
    vector.x = 1.0;       //2 cycles[/size]

2)
     data_foo();  //calling a pointer to such machine code array
                // where only "ret" was contained 
                  //12 cycles[/size]
 
3)
    vector.x = 1.0; [/size]
    data_foo();
                     //mixing one with the second
                    // few hundred cycles - with unknown reason



Without knowing what the entirety of your program looks like, we can only speculate what you might be seeing. If you post the full program's disassembly (including the address of each function) we might be able to narrow down the issue more easily.

Everything matters. If 'vector' is a stack-allocated variable or a heap variable, that matters. The address of each function. All of the rest of the code that you've omitted also matters.

 

I know but i got only notes now, lost the source  - can do test later, but i remember it was like that -assigment took 2 cycles , ret from data 12 cycles and one with another few hundred cycles instead of 14 or so..

0

Share this post


Link to post
Share on other sites

For the vector/data_foo() example, I'm guessing data_foo() jumps to an address in .data. That causes the bad performance. If you try to jump to code near data, you often force waiting for that data to be flushed far enough in the memory heirarchy to reach a unified portion of memory. Depending on your system's design, that worst case could technically require writing data all the way out to main memory. Best case is probably store to load forwarding not caring about icache/dcache designation, but even then you're likely still forcing a sync and taking the perf hit that entails.

 

If you're really interested in this stuff, you can read about dynamic recompilation. It's largely avoided nowadays, so you're likely going to find information relating to Pentium 3 and Athlon if not even older than that. You might even find open source emulators/interpreters that still use dynamic recompilation since I know there was a lot of love for dynamic recompilation like 10-15 years ago.

0

Share this post


Link to post
Share on other sites

I did some test (it is a somewhat 'casual' test but i got no energy to

rewrite it 

 

#include <stdio.h>
 
char rtdsc_bin[] =
{
 0x0f, 0x31,
 0xc3
};
 
 
int f(int* x)
{
  x[0] = 10;
  x[1] = 20;
 
}
 
 
char f_bin[] =      //f() body + rdtsc commnd
{
 0x55,
 0x89, 0xE5,
 0x8B, 0x45, 0x08,
 0xC7, 0x00, 0x0A, 0x00, 0x00, 0x00,
 0x8B, 0x45, 0x08,
 0x83, 0xC0, 0x04,
 0xC7, 0x00, 0x14, 0x00, 0x00, 0x00,
 0x5D,
 0x0f, 0x31,  //rdtsc here
 0xC3,
};
 
void main()
{
 
   int (*foo)() ;
   int (*food)(int*) ;
 
   foo = rtdsc_bin;
 
   int a = foo();
   int b = foo();
 
   printf(" %d ",b-a);
 
   static int i[2];
   /////////////////////////////
   food = f_bin;
 
   int c = food(i);
   int d = food(i);
 
   printf(" %d ",d-c);
 
   printf("\n %d ",i[0]);
   printf("\n %d ",i[1]);
 
}
 

 

and im at least happy with that , seem to be no slowdown

probably here in mingw 

 

results are like

 

112 119

10

20

 

112 126

10

20

 

112 is probably rtdsc cost itself (?) the rest of the function f

takes only few cycles probably - no applied slowdown noticable

(as far as i can be sure) so this machine code trick (one of my favourites) still work

0

Share this post


Link to post
Share on other sites

If you're going to put code in the data section, at least pad to a new cache line (often 64 bytes). Ideally, you'd give the code its own page.

0

Share this post


Link to post
Share on other sites

If you're going to put code in the data section, at least pad to a new cache line (often 64 bytes). Ideally, you'd give the code its own page.

was not aligned even to 4

 

SECTION .data   align=4 noexecute                       ; section number 2, data
 
_rtdsc_bin:                                             ; byte
        db 0FH, 31H, 0C3H                               ; 0000 _ .1.
 
_f_bin:                                                 ; byte
        db 55H, 89H, 0E5H, 8BH, 45H, 08H, 0C7H, 00H     ; 0003 _ U...E...
        db 0AH, 00H, 00H, 00H, 8BH, 45H, 08H, 83H       ; 000B _ .....E..
        db 0C0H, 04H, 0C7H, 00H, 14H, 00H, 00H, 00H     ; 0013 _ ........
        db 5DH, 0FH, 31H, 0C3H, 00H                     ; 001B _ ].1..
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0