Why does the compiler optimize away shared memory reads due to strncmp() even if volatile keyword is used?

爷,独闯天下 提交于 2019-12-05 20:14:58

By writing (char *)mem you are telling the strncmp function that it it is actually not a volatile buffer. And indeed, strncmp and the other C library functions are not designed to work on volatile buffers.

You do in fact need to modify your code to not use C library functions on volatile buffers. Your options include:

  • Write your own alternative to the C library function that works with volatile buffers.
  • Use a proper memory barrier.

You've gone with the first option; but think about what would happen if the other process modified the memory in between your four reads. To avoid this sort of problem you'd need to use the second option, an inter-process memory barrier -- in which case the buffer no longer needs to be volatile and you can go back to using the C library functions. (The compiler must assume that the barrier check might change the buffer).

6.7.3 Type qualifiers

6 [...] If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.133)

133) This applies to those objects that behave as if they were defined with qualified types, even if they are never actually defined as objects in the program (such as an object at a memory-mapped input/output address).

That is exactly what you observe in your code. The compiler is basically optimizing your code under the wild freedom of "the behavior is undefined anyway".

In other words, it is impossible to correctly apply strncmp directly to volatile data.

What you can do is either implement your own comparison that does not discard volatile qualifier (which is what you've done already), or use some volatile-aware method of copying volatile data to non-volatile storage and they apply strncmp to the latter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!