Songjinshan's Blog

nginx-0.8.6的shmtx代码分析

Aliasing, pointer casts and gcc 3.3.

songjinshan posted @ 2009年8月24日 02:20 in C , 3141 阅读

I came across a gcc optimization problem. The prototype code is:

 

#include <stdio.h>
#include <stdint.h>

int main (void)
{
        uint64_t n;
        double val;

        n = 0x4087e00000000000LL;
        val = *(double *)&n;
        printf("%f\n", val);

    return 0;
}

Here's the result:

$ gcc test1.c -Wall
$ ./a.out
764.000000

$ gcc test1.c -Wall -O3
test1.c: In function ‘main’:
test1.c:10: warning: dereferencing type-punned pointer will break strict-aliasing rules
$ ./a.out
0.000000

$ gcc test1.c -Wall -O3 -fno-strict-aliasing
$ ./a.out
764.000000
 

I searched issues about strict-aliasing and found this article from http://mail-index.netbsd.org/tech-kern/2003/08/11/0001.html

Subject: Aliasing, pointer casts and gcc 3.3.
To: None <tech-kern@netbsd.org>
From: Krister Walfridsson <cato@df.lth.se>
List: tech-kern
Date: 08/11/2003 23:16:48

I have seen some commits that "fix" gcc 3.3 alias warnings, that does not
give me warm fuzzy feelings (the commits that is), and I have alse seen a
lot of confusion about aliasing (and ISO C in general) on different
mailing lists, so I have tried to explain some of the issues that I know
have/will bite us.

Apologies if this is too elementary...



ALIASING
========

What is aliasing?
=================
The hardware-centric view of pointers is that they can point at any
memory,
so a write through a pointer may change any variable in a program:

    int i = 23;
    *f = 5;
    /* We don't know what value i has at this point. */

We cannot know what value i has, since the pointers &i and f may point
at the same address (that is what ISO C means when it say that &i and f
may alias).

This prevents many types of optimizations, and it makes a real difference
since most pointers in real life cannot point on the same position.  ISO C
improves the situation (for the compiler) by roughly saying "pointers of
different types cannot point to the same address".

    int
    foo(float *f) {
            int i = 23;
            *f = 5.0;
            /* A float* cannot point on the same address as int*. */
            return i * 2;
    }

So the compiler may optimize this to

    int
    foo(float *f) {
            *f = 5.0;
            return 46;
    }

The ISO specification does not really prevent pointers to point to the
same address -- it specifies that the result is undefined when you
dereference a pointer that points to an object of a different
(incompatible) type.  So the following example is OK:

    int i = 23, *tmp;
    tmp = (int*)f;
    *tmp = 5;
    /* We don't know what value i has at this point. */

But note the important difference that we are actually writing the memory
position as an "int" and not as a "float".


There exist an important exception to the rule above:  char* may alias all
types (too much code would break if ISO had prevented this...)


There are cases where you wish to access the same memory as different
types:

    float *f = 2.718;
    printf("The memory word has value 0x%08x\n", *((int*)f));

You cannot do that in ISO C, but gcc has an extension in that it
considers memory in unions as having multiple types, so the following
will work in gcc (but is not guaranteed to work in other compilers!)

    union {
        int i;
        float f;
    } u;
    u.f = 2.718;
    printf("The memory word has value 0x%08x\n", u.i);

One bieffect of this is that gcc may miss optimization opportunities
when you use union-heavy constructs.



What the standard says [*]
==========================
The aliasing rules are stated in clause 6.5 (Expressions):

 7 An object shall have its stored value accessed only by an lvalue
   expression that has one of the following types: {footnote 73}

     a type compatible with the effective type of the object,

     a qualified version of a type compatible with the effective type of
     the object,

     a type that is the signed or unsigned type corresponding to the
     effective type of the object,

     a type that is the signed or unsigned type corresponding to a
     qualified version of the effective type of the object,

     an aggregate or union type that includes one of the aforementioned
     types among its members (including, recursively, a member of a
     subaggregate or contained union), or

     a character type.

 {footnote 73} The intent of this list is to specify those circumstances
 in which an object may or may not be aliased.



The gcc warnings
================
gcc may warn for some constructs that break the aliasing rules, but not
all of them (or not even most of them!), so a warning-free source code
does not give you any guarantee.

The most common warning you will see is probably "dereferencing type-
punned pointer will break strict-aliasing rules".  The place where it
warns is in general not wrong -- what gcc tries to tell you is that you
will break the aliasing rules when you dereference the pointer later
(unless you cast it back to its original type first).  This warning
should be interpreted as saying that your interfaces are badly designed,
and the correct way to avoid the warning is to redesign them in a way
where you do not need to cast between conflicting types.  (Even if you
often can make this warning go away by changing void** to void*...)




POINTER CASTS AND ALIGNMENT
===========================

The problem
===========
Many architectures requires that pointers are correctly aligned when
accessing objects bigger than a byte.  There are however many places
in system code where you receive unaligned data (e.g. the network stacks)
so you need to fix it up:

    char* data;
    struct foo_header *tmp, header;

    tmp = data + offset;
    memcpy(&header, tmp, sizeof(header));

    if (header.len < FOO)
    [...]

But this does not work...  The reason is that the behavior is undefined
when you assign an unaligned value to a pointer that points to a type
that need to be aligned.  What happens in the example above is that gcc
notices that tmp and header must be aligned, so it may use an inlined
memcpy that uses instructions that assumes aligned data.

The correct way to fix this is not to use the foo_header pointer

    char* data;
    struct foo_header header;

    memcpy(&header, data + offset, sizeof(header));

    if (header.len < FOO)
    [...]

The original example above might look silly, but this has bitten us a
couple of times already...



What the standard says [*]
==========================
The pointer alignment requirements are stated in clause 6.3.2.3
(Pointers):

 7 A pointer to an object or incomplete type may be converted to a pointer
   to a different object or incomplete type. If the resulting pointer is
   not correctly aligned {footnote 57} for the pointed-to type, the
   behavior is undefined. Otherwise, when converted back again, the result
   shall compare equal to the original pointer. [...]

 {footnote 57} In general, the concept "correctly aligned" is transitive:
 if a pointer to type A is correctly aligned for a pointer to type B,
 which in turn is correctly aligned for a pointer to type C, then a
 pointer to type A is correctly aligned for a pointer to type C.




CONCLUSION
==========
ISO C is not your grandfather's C, and it is wrong to think of it as a
high-level machine language...

Pointer casts are evil (both explicit and implicit casts), and you
should think twice before adding a pointer cast to the code...



[*] The standard references are from ISO/IEC 9899:1999, but the older
ANSI/ISO standard says essentially the same thing.


   /Krister

 

Avatar_small
windzou264475@163.co 说:
2009年12月27日 07:50

请问北软好吗?不过在网上听到听到负面消息的,请你如实地告诉我,谢谢

Avatar_small
seo service UK 说:
2024年5月08日 17:41

Thanks for sharing this amazing post. Logos are among the first things that any visitor comes across when going through a website for the first time. This is why it is absolutely crucial that their experience is memorable so you need a quality 

Avatar_small
토토사이트추천 说:
2024年5月08日 18:58

It a fabulous blog post As i looked at caused by have the application. Advise everything that Need be to find expectation on potential future you certainly will persist designed for writing a great wonderful blog post.

Avatar_small
토토사이트홍보 说:
2024年5月08日 18:59

If more people that write articles really concerned themselves with writing great content like you, more readers would be interested in their writings. Thank you for caring about your content.

Avatar_small
토토사이트 说:
2024年5月08日 18:59

I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back down the road. Cheers

Avatar_small
먹튀뱅크 说:
2024年5月08日 19:00

I was suggested this web site through my cousin. I’m not certain whether this put up is written through him as no one else recognize such exact approximately my difficulty. You’re wonderful! Thank you!

Avatar_small
메이저사이트목록 说:
2024年5月08日 19:01

I appreciated how flexible the team at amcauto.co was when it came to scheduling appointments and test drives. They were always willing to work around my schedule.

Avatar_small
토토홀리 说:
2024年5月08日 19:01

I was suggested this web site through my cousin. I’m not certain whether this put up is written through him as no one else recognize such exact approximately my difficulty. You’re wonderful! Thank you!

Avatar_small
토토사이트 说:
2024年5月08日 19:03

I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back down the road. Cheers

Avatar_small
메리트카지노 说:
2024年5月08日 19:03

My spouse and I absolutely love your blog and find a lot of your post’s to be exactly what I’m looking for. Do you offer guest writers to write content in your case? I wouldn’t mind writing a post or elaborating on a few of the subjects you write with regards to here. Again, awesome web site!

Avatar_small
토토시대 说:
2024年5月08日 19:04

I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to create your theme? Great work!

Avatar_small
메이저놀이터순위 说:
2024年5月08日 19:05

Oh my goodness! an amazing article dude. Thank you Nevertheless I am experiencing situation with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting identical rss downside? Anybody who is aware of kindly respond. Thnkx

Avatar_small
먹튀365 说:
2024年5月08日 19:06

This may be the proper weblog for desires to find out about this topic. You know so much its virtually challenging to argue along (not too I really would want…HaHa). You definitely put a new spin for a topic thats been revealed for some time. Excellent stuff, just great!

Avatar_small
먹튀마루 说:
2024年5月08日 19:06

Prevention is key, which is why we offer maintenance plans. We help you stay ahead of potential hazards and costly repairs with regular cleaning and inspections.

Avatar_small
메이저토토사이트 说:
2024年5月08日 19:07

I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.

Avatar_small
먹튀타운 说:
2024年5月08日 19:08

Operational Challenges:New Rabbit's continuous address changes may pose inconveniences for users seeking a stable and reliable webtoon experience.

Avatar_small
먹튀신고 说:
2024年5月08日 19:08

It a fabulous blog post As i looked at caused by have the application. Advise everything that Need be to find expectation on potential future you certainly will persist designed for writing a great wonderful blog post.

Avatar_small
먹튀폴리스 说:
2024年5月08日 19:12

I?ve recently started a website, the information you offer on this website has helped me tremendously. Thanks for all of your time & work.

Avatar_small
온라인카지노 说:
2024年5月08日 19:13

I think one of your commercials triggered my web browser to resize, you may well want to put that on your blacklist.

Avatar_small
토토사이트 说:
2024年5月08日 19:15

Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better. The post is written in very a good manner and it contains many useful information for me. Thank you very much and will look for more postings from you.

Avatar_small
메이저사이트순위 说:
2024年5月08日 19:15

Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better. The post is written in very a good manner and it contains many useful information for me. Thank you very much and will look for more postings from you.

Avatar_small
먹튀검증업체 说:
2024年5月08日 19:16

I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.

Avatar_small
안전놀이터가입 说:
2024年5月08日 19:16

Impressive web site, Distinguished feedback that I can tackle. Im moving forward and may apply to my current job as a pet sitter, which is very enjoyable, but I need to additional expand. Regards.

Avatar_small
ok토토먹튀검증 说:
2024年5月08日 19:17

Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking

Avatar_small
파워볼사이트 说:
2024年5月08日 19:18

It a fabulous blog post As i looked at caused by have the application. Advise everything that Need be to find expectation on potential future you certainly will persist designed for writing a great wonderful blog post.

Avatar_small
안전놀이터 说:
2024年5月08日 19:18

Impressive web site, Distinguished feedback that I can tackle. Im moving forward and may apply to my current job as a pet sitter, which is very enjoyable, but I need to additional expand. Regards. <a href="https://totositestar.com">안전놀이터</a>

Avatar_small
메이저놀이터 说:
2024年5月08日 19:19

This may be the proper weblog for desires to find out about this topic. You know so much its virtually challenging to argue along (not too I really would want…HaHa). You definitely put a new spin for a topic thats been revealed for some time. Excellent stuff, just great!

Avatar_small
먹튀검증 说:
2024年5月08日 19:20

Hi, i feel that i noticed you visited my website so i got here to ?go back the prefer?.I’m trying to to find things to enhance my website!I guess its ok to use some of your ideas!!

Avatar_small
토토사이트 说:
2024年5月08日 19:20

Thanks, I have all the files, is there any way that the geometry and mesh can be connected again? Now, I can import to a new .wbpj each file independently, so if I need to remesh my model, I need to change the geometry and start meshing from scratch.

Avatar_small
메이저사이트 说:
2024年5月08日 19:21

Even nevertheless there are lots of decision methods with the purpose of lookup used for non published numbers, but you would approximating rapid stately results to you possibly will look forward to in, you possibly will necessitate with the purpose of desire particular sort of swap telephone search company.

Avatar_small
토토사이트검증 说:
2024年5月08日 19:22

I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.

Avatar_small
먹튀검증 说:
2024年5月08日 19:22

Even nevertheless there are lots of decision methods with the purpose of lookup used for non published numbers, but you would approximating rapid stately results to you possibly will look forward to in, you possibly will necessitate with the purpose of desire particular sort of swap telephone search company.

Avatar_small
카지노헌터 说:
2024年5月08日 19:23

Impressive web site, Distinguished feedback that I can tackle. Im moving forward and may apply to my current job as a pet sitter, which is very enjoyable, but I need to additional expand. Regards.

Avatar_small
카지노세상 说:
2024年5月08日 19:23

Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking

Avatar_small
메이저토토사이트 说:
2024年5月08日 19:24

Useful information. Fortunate me I discovered your web site by accident, and I am stunned why this accident didn’t came about in advance! I bookmarked it.

Avatar_small
baccarat friends 说:
2024年5月08日 19:24

I truly contented to come all over your special data. I like this web page.

Avatar_small
먹튀검증업체 说:
2024年5月08日 19:25

Two full thumbs up for this magneficent article of yours. I've truly delighted in perusing this article today and I figure this may be outstanding amongst other article that I've perused yet. If it's not too much trouble keep this work going ahead in a similar quality.

Avatar_small
샌즈카지노 说:
2024年5月09日 00:20

Thank you for every other magnificent article. Where else may just anyone get that kind of info in such an ideal manner of writing? I have a presentation subsequent week, and I am at the search for such info.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter