接続数

COUNTER367659FROM 2012/5/16

MISRA-C diary(C言語日誌)

12345Next
2019/06/01

C言語って難しいのか簡単なのか

Tweet ThisSend to Facebook | by kaizen

C言語って難しいのか簡単なのか

C言語が一番の専門ではありません。


ちょっとしたテクリで速度改善Tips
https://qiita.com/taptappun/items/83578a6ab3546ec1dc2d

1. 誤植

後値インクリメント
->
後置インクリメント

編集リクエスト送付

2. 誤解

ちょっとだけ速くなる書き方
int i = 1;
++i

後置インクリメントだと内部でインスタンスの生成が発生するので、ちょっと処理に時間がかかるようです。ただ現在ではコンパイラの発達により、どちらでもほとんどが出ないことが多いです

後置インクリメントと前置インクリメントで、インスタンスの生成の有無は、C、C++では過去に例を知りません。

他の言語での設計は未確認。

対策

C, C++はコンパイラ、コンパイル結果を比較してみればわかる。

C, C++は過去のプログラムを無駄にしないために古いものも残しているかもしれない。


21:16 | Impressed! | Voted(0) | Comment(0)
2019/05/26

言語習得

Tweet ThisSend to Facebook | by kaizen

なぜ言語習得で爆発四散するか

プログラミング学習メモ1
https://qiita.com/Y_Tanimachi/items/9574250e05f36b02df69


言語は、何かの目的のために使う道具です。

言語習得自体を目的にはしない方がよいでしょう。

例えば、WEBでうごかしたいものがあるなら、 XXX言語とか。

WEBで体系的に表示したいものがあり、それがYY分野の資料なら、ZZ言語とか。

目的が何かで、習得するのによい言語があるかもしれません。

目的のない言語学習は、爆発四散するかも。

じゃ、言語について目標にしてはいけないかというとそうではないかも。

自分がC言語を勉強しはじめたのは、Cコンパイラが書きたかったから。

それまで、アセンブラかCOBOLかFORTRANかBASICでプログラム書いていて、
プログラムの自動生成とか書いて少しでもプログラム書くの楽になりたかった。
Cコンパイラを書いて、自動生成とか、もう一段抽象化してかければ、効率的になるかもと思い、
コンパイラを書いて、自動生成とか


19:05 | Impressed! | Voted(0) | Comment(0)
2019/05/07

プログラマ以外の人がプログラムを書き始めるために(かきかけ)

Tweet ThisSend to Facebook | by kaizen

プログラマ以外の人がプログラムを書き始めるために

プログラマ以外の人が、プログラムを書き始めるきっかけを、プログラムの具体例を含めていくつか紹介します。

  1. ゲームはするより作るのが楽しい。

というとかっこいいです。
実際は、ゲームを買うお金がないから、自分で作るしかなかったというのが実情です。

最初に、アセンブラで組んだのもゲーム。

一番最初はCASIOの関数電卓。

その次が、TRS-80というZ80という8bit CPUを積んだパソコン。

PC-9801でも、


08:36 | Impressed! | Voted(0) | Comment(0)
2019/05/05

clang

Tweet ThisSend to Facebook | by kaizen

clang を docker container で動かす
https://qiita.com/syoyo/items/8d55809d3c8243e8f202

llvm-clang環境のDockerを作ってDocker Hubにpushした。
https://qiita.com/nak1114/items/8cc97fa405be14a34181


08:52 | Impressed! | Voted(0) | Comment(0)
2019/04/29

名古屋で自動車関係のソフトウェア設計する際にあるといい知識

Tweet ThisSend to Facebook | by kaizen

名古屋で自動車関係のソフトウェア設計する際にあるといい知識

経済産業省の中核人材プロジェクト「組み込み人材」のプロジェクトマネージャをしていたものです。

名古屋で自動車関係のソフトウェア設計する際にあるといい知識について整理したことがあります。

その際の、資料一覧を更新してみます。

OS

OSEK

ISO 

AUTOSAR

Autosarは、国際規格OSEK OSに基づいて、団体規格として制定したものである。WTO/TBT協定上の根拠はOSEK OSに基づいていることによる。

AUTOSARとOSEKを別物だとするのは、国際規格とその一つの実現という別の次元のものを、同じ軸に並べて別物と言っているにすぎない。

参考文献

1 自動車技術ハンドブック

1.1 自動車工学ハンドブック 第1分冊 基礎・理論 編

http://www.jsae.or.jp/jsae70th/project/docu/hand_1.pdf

1.2 自動車技術ハンドブック第2分冊 環境・安全・情報 編

http://www.jsae.or.jp/jsae70th/project/docu/hand_2.pdf

1.3 自動車技術ハンドブック第3分冊 人間工学 編

http://www.jsae.or.jp/jsae70th/project/docu/hand_3.pdf

1.4 自動車技術ハンドブック第4分冊 設計(デザイン・車体) 編

1.5 自動車技術ハンドブック第5分冊 設計(パワートレイン)編

1.6 自動車技術ハンドブック第6分冊 設計(シャシ) 編

1.7 自動車技術ハンドブック第7分冊 設計(EV・ハイブリッド) 編

1.8 自動車技術ハンドブック第8分冊 試験・評価(パワートレイン) 編

1.9 自動車技術ハンドブック第9分冊 試験・評価(車両) 編

1.10 自動車技術ハンドブック第10分冊 生産・品質 編

2 日本の自動車規格DVD-ROM

2017 制定

e408-17 自動車部品-パワートレイン用オイルクーラ放熱性能試験方法
m362-17 自動車用ディーゼル機関潤滑油-燃費試験方法

2017 改正

c305-1-17 自動車部品―鉛フリーホイールバランスウェイト―第1部:クリップ式
c305-2-17 自動車部品―鉛フリーホイールバランスウェイト―第2部:接着式
c466-17 自動車-ブレーキ停止距離測定方法
c704-17 自動車―低速転回時の操だ力試験方法
d609-17 自動車部品-自動車用電線の電流容量
d612-3-17 自動車部品―ヒューズ―第3部:ブレード形ヒューズ
d802-17 自動車の空調用語
f102-17 自動車部品-六角ナット
f118-17 自動車部品-座金組込み六角ナット
f205-17 自動車部品―配管・配線用クリップ
m312-17 プラスチック成形部品の試験方法
m319-17 ホース試験通則
m355-17 自動車用ディーゼル機関潤滑油
z115-17 自動車部品-エアコンディショナのコンデンサ放熱性能試験方法
z116-17 自動車部品-エアコンディショナのエバポレータ冷却性能試験方法
z120-17 自動車用部品-エアコンディショナのサブクールコンデンサ放熱性能試験方法
TP
tp-17001 自動車-自動車用C言語のガイドライン(MISRA-C)の遵守のための逸脱ガイダンス
TP改正
tp-01002-17 自動車-自動車用C言語利用のガイドライン(第2版)-ガイドライン及びMISRA準拠のための逸脱許可

2016 収録された制定規格(9件)

D015-1-15 D015-2-16 D015-4-16 D015-5-15 D 624-15 E 013-15 E 014-15 E 015-16 F 126-16
Automobiles - Clock Extension Peripheral Interface (CXPI) - Part 1: General Information and UseCases Definition
Automobiles - Clock Extension Peripheral Interface (CXPI) - Part 2: Transport Protocol andNetwork Layer service
Automobiles - Clock Extension Peripheral Interface (CXPI) - Part 4: Unified Diagnostic Services onClock Extension Peripheral Interface Automobiles - Clock Extension Peripheral Interface (CXPI) - Part 5: Protocol Conformance Testspecification
Automotive parts – High-voltage cables
Automobiles – Analytical procedure for measurement of ammonia concentration in raw exhaust gas
Automobiles – Requirements and evaluation methods of chassis dynamometers – Supplement to fuel consumption tests
Automobiles - Road load determination method for variation model vehicles using chassis dynamometer
Automotive parts - Hexagon bolts with flange

2016 収録された改正規格(3件)

C 441-15 D015-3-15 D 603-16
Service Brake Structural Durability Bench Test Procedure
Automobiles - Clock Extension Peripheral Interface (CXPI)-Part 3: Protocol specification Automotive parts - Unscreened aluminum conductor low-voltage cables

3 ボッシュ自動車ハンドブック 日本語

Bosch Automotive Handbook 9th Edition

4

5 機械関係

5.1 機械工学便覧DVDーROM版

http://gigaplus.makeshop.jp/jsmebooks/contents/5501_contents.pdf

5.2 機械工学ハンドブック


11:32 | Impressed! | Voted(0) | Comment(0)
2019/04/21

C++ coding standard

Tweet ThisSend to Facebook | by kaizen

C++ coding standard

MISRA C++

Motor Industry Software Reliability Association

Cert C++

AUTOSAR C++14

Modern C++

RainerGrimm/ModernesCpp
https://github.com/RainerGrimm/ModernesCpp

No New New: Raw Pointers Removed from C++, , 26 March 2018
http://www.modernescpp.com/index.php/no-new-new

C++ Core Guidelines

The C++ Core Guidelines for Safer Code
https://meetingcpp.com/mcpp/slides/2018/TheC++CoreGuidelinesForSaverCode.pdf


19:15 | Impressed! | Voted(0) | Comment(0)
2019/03/26

C++

Tweet ThisSend to Facebook | by kaizen

[Cline 2009] Cline, Marshall. C++ FAQ Lite—Frequently Asked Questions. 1991-2009.

should be replaced

http://www.parashift.com/c++-faq/
https://isocpp.org/faq
://isocpp.org/faq



10:22 | Impressed! | Voted(0) | Comment(0)
2019/03/25

Bibliography

Tweet ThisSend to Facebook | by kaizen

[Abrahams 2010] Abrahams, David. Error and Exception Handling, #7. Boost Library. 2010.

[Banahan 2003] Banahan, Mike. The C Book . 2003.

[Barney 2010] Barney, Blaise. POSIX Threads Programming. Lawrence Livermore National Security, LLC. 2010.

[Becker 2008] Becker, Pete. Working Draft, Standard for Programming Language C++. April 2008.

[Becker 2009] Becker, Pete Working Draft, Standard for Programming Language C++. September 2009.

[Black 2007] Black, Paul E.; Kass, Michael; & Koo, Michael. Source Code Security Analysis Tool Functional Specification Version 1.0. Special Publication 500-268. Information Technology Laboratory (ITL). May 2007.

[Cline 2009] Cline, Marshall. C++ FAQ Lite—Frequently Asked Questions. 1991-2009.

[CodeSourcery 2016a] CodeSourcery, Compaq, EDG, HP, IBM, Intel, Red Hat, SGI, et al. Itanium C++ ABI. December 2016 [accessed].

[CodeSourcery 2016b] CodeSourcery, Compaq, EDG, HP, IBM, Intel, Red Hat, SGI, et al. Itanium C++ ABI (Revision: 1,86). December 2016 [accessed].

[Coverity 2007] Coverity. Coverity Prevent User's Manual (3.3.0). 2007.

[CWE] MITRE. Common Weakness Enumeration – A Community-Developed Dictionary of Software Weakness Types.

[Dewhurst 2002] Dewhurst, Stephen C. C++ Gotchas: Avoiding Common Problems in Coding and Design. Addison-Wesley Professional. 2002.

[Dewhurst 2005] Dewhurst, Stephen C. C++ Common Knowledge: Essential Intermediate Programming. Addison-Wesley Professional. 2005.

[DISA 2015] DISA. Application Security and Development Security Technical Implementation Guide, Version 3, Release 10. Accessed April 2015.

[DISA 2016] DISA. Application Security and Development Security Technical Implementation Guide, Version 4, Release 1. Accessed January 2017.

[DISA 2018] DISA. Application Security and Development Security Technical Implementation Guide, Version 4, Release 8. Accessed January 2019.

[Dowd 2006] Dowd, Mark; McDonald, John; & Schuh, Justin. Attacking delete and delete[] in C++. In The Art of Software Security Assessment. Addison-Wesley Professional. 2006.

[Fortify 2006] Fortify Software Inc. Fortify Taxonomy: Software Security Errors. 2006.

[FSF 2005] Free Software Foundation. GCC Online Documentation. 2005.

[Gamma 1994] Gamma, Erich; Helm, Richard; Johnson, Ralph, & Vlissides, John. Design Patterns Elements of Reusable Object Oriented Software. Addison-Wesley Professional. 1994.

[GNU 2016] gnu.org. GCC, the GNU Compiler Collection: Declaring Attributes of Functions. December 2016 [accessed].

[Goldberg 1991] Goldberg, David. What Every Computer Scientist Should Know About Floating-Point Arithmetic. Sun Microsystems. March 1991.

[Graff 2003] Graff, Mark G. & Van Wyk, Kenneth R. Secure Coding: Principles and Practices. O'Reilly. 2003. ISBN 0596002424.

[Henricson 1997] Henricson, Mats & Nyquist, Erik. Industrial Strength C++. Prentice Hall PTR. 1997. ISBN 0-13-120965-5.

[Hinnant 2005] Hinnant, Howard. RValue Reference Recommendations for Chapter 20. N1856=05-0116. August 2005.

[Hinnant 2015] Hinnant, Howard. Reply to "std::exception Why what() is returning a const char* and not a string?ISO C++ Standard—Discussion. June 2015.

[IEC 60812 2006] Analysis techniques for system reliability - Procedure for failure mode and effects analysis (FMEA), 2nd ed. IEC 60812. IEC. January 2006.

[IEEE Std 610.12 1990] IEEE.  IEEE Standard Glossary of Software Engineering Terminology. 1990.


[IEEE Std 1003.1:2013] IEEE & The Open Group. Standard for Information Technology—Portable Operating System Interface (POSIX). Base Specifications. Issue 7. 2013.

[INCITS 2012] INCITS Document number N3396= 12-0096. Dynamic memory allocation for over-aligned data. 2012. 

[INCITS 2014] INCITS PL22.16 & ISO WG21 C++ Standards Committee, Library Working Group (LWG). C++ Standard Library Active Issues List (Revision R88). N3967. 2014.

[Internet Society 2000] The Internet Society. Internet Security Glossary (RFC 2828). 2000.

[ISO/IEC 9899-1999] ISO/IEC 9899-1999. Programming Languages — C, Second Edition.1999.

[ISO/IEC 9899:2011] ISO/IEC. Programming Languages—C, 3rd ed. ISO/IEC 9899:2011. 2011.

[ISO/IEC 14882-1998] ISO/IEC 14882-1998. Programming Languages — C++, First Edition.1998.

[ISO/IEC 14882-2003] ISO/IEC 14882-2003. Programming Languages — C++, Second Edition.2003.

[ISO/IEC 14882-2011] ISO/IEC 14882-2011. Programming Languages — C++, Third Edition.2011.

[ISO/IEC 14882-2014] ISO/IEC 14882-2014. Programming Languages — C++, Fourth Edition.2014.

[ISO/IEC N3000 2009] Working Draft, Standard for Programming Language C++. November 2009.

[ISO/IEC TR 24772:2013] ISO/IEC. Information Technology—Programming Languages—Guidance to Avoiding Vulnerabilities in Programming Languages through Language Selection and Use. TR 24772-2013. ISO. March 2013.

[ISO/IEC TS 17961:2012] ISO/IEC TS 17961. Information Technology—Programming Languages, Their Environments and System Software Interfaces—C Secure Coding Rules. ISO. 2012.

[Jack 2007] Jack, Barnaby. Vector Rewrite Attack. Juniper Networks. May 2007.

[Kalev 1999] Kalev, Danny. ANSI/ISO C++ Professional Programmer's Handbook. Que. Corporation. 1999

[Lea 2000] Lea, Doug. Concurrent Programming in Java, 2nd Edition. Addison-Wesley Professional. 2000.

[Lions 1996] Lions, J. L. ARIANE 5 Flight 501 Failure Report. European Space Agency (ESA) & National Center for Space Study (CNES). July 1996.

[Lions 1996] Lions, J. L. ARIANE 5 Flight 501 Failure Report. European Space Agency (ESA) & National Center for Space Study (CNES). July 1996.

[Lockheed Martin 2005] Lockheed Martin. Joint Strike Fighter Air Vehicle C++ Coding Standards for the System Development and Demonstration Program. Document Number 2RDU00001, Rev C. December 2005.

[Meyers 1996] Meyers, Scott. More Effective C++: 35 New Ways to Improve Your Programs and Designs. Addison-Wesley. 1996.

[Meyers 2001] Meyers, Scott. Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library. Addison-Wesley Professional. 2001.

[Meyers 2005] Meyers, Scott. Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition). Addison-Wesley Professional. 2005.

[Meyers 2014] Meyers, Scott. Reply to The Drawbacks of Implementing Move Assignment in Terms of Swap [blog post]. The View from Aristeia: Scott Meyers' Professional Activities and Interests. 2014.

[Microsoft 2010] STL std::string class causes crashes and memory corruption on multi-processor machines. 2010.

[MISRA 2004] MIRA Limited. MISRA C2004 Guidelines for the Use of the C Language in Critical Systems. MIRA Limited. ISBN 095241564X. October 2004.

[MISRA 2008] MISRA Limited. MISRA C++ 2008 Guidelines for the Use of the C++ Language in Critical Systems. ISBN 978-906400-03-3 (paperback);  ISBN 978-906400-04-0 (PDF). June 2008.

[MITRE 2007] MITRE. Common Weakness Enumeration, Draft 9. April 2008.

[MITRE 2008a] MITRE. CWE ID 327Use of a Broken or Risky Cryptographic Algorithm. 2008.

[MITRE 2008b] MITRE. CWE ID 330Use of Insufficiently Random Values. 2008.

[MITRE] MITRE. Common Weakness Enumeration, Version 1.8. February 2010.

[MSDN 2010] Microsoft Developer Network. CryptGenRandom Function. December 2016 [accessed].

[MDSN 2016] Microsoft Developer Network. nothrow (C++). December 2016 [accessed].

[NIST 2006] NIST. SAMATE Reference Dataset. 2006.

[Open Group 2013] The Open Group. The Open Group Base Specifications Issue 7, IEEE Std 1003.1, 2013 Edition. 2013.

[Open Group 2008] The Open Group. The Open Group Base Specifications Issue 7, IEEE Std 1003.1, 2008 Edition. 2008.

[Open Group 2004] The Open Group. The Open Group Base Specifications Issue 6, IEEE Std 1003.1, 2004 Edition. 2004.

[Plum 1991] Plum, Thomas. C++ Programming. Plum Hall, Inc. November 1991. ISBN 0911537104.

[Quinlan 2006] Quinlan, Dan; Vuduc, Richard; Panas, Thomas; Härdtlein, Jochen; & Sæbjørnsen, Andreas. Support for Whole-Program Analysis and the Verification of the One-Definition Rule in C++. 27-35. Page 500-262. In Proceedings of the Static Analysis Summit. July 2006.

[Rohlf 2009] Rohlf, Chris. Fun with erase (). 2009.

[Saks 1999] Saks, Dan. const T vs.T constEmbedded Systems Programming. February 1999. Pages 13-16.

[Saks 2007] Saks, Dan. Sequence PointsEmbedded Systems Design. 2007.

[Seacord 2005] Seacord, Robert C. Secure Coding in C and C++. Addison-Wesley. 2005. ISBN 0321335724.


[Seacord 2013] Seacord, Robert C. Secure Coding in C and C++, Second Edition. Addison-Wesley. 2013.

[Sebor 2004] Sebor, Martin. C++ Standard Core Language Active Issues, Revision 68. 2010.

[SGI 2006] Silicon Graphics, Inc. basic_string<charT, traits, Alloc>Standard Template Library Programmer's Guide. 2006.

[Steele 1977] Steele, G. L. Arithmetic shifting considered harmful. SIGPLAN Notices. Volume 12. Issue 11. November 1977. Pages 61-69.

[Stroustrup 1997] Stroustrup, Bjarne. The C++ Programming Language, Third Edition. Addison-Wesley. 1997. ISBN 978-0201700732.

[Stroustrup 2006] Stroustrup, Bjarne. C++ Style and Technique FAQ. 2006. December 2016 [accessed].

[Stroustrup 2001] Stroustrup, Bjarne. Exception Safety: Concepts and Techniques. AT&T Labs. 2001.

[Sun 1993] Sun Security Bulletin #00122. 1993.

[Sutter 2000] Sutter, Herb. Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions. Addison-Wesley Professional. 2000. ISBN 0201615622.

[Sutter 2001] Sutter, Herb. More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions. Addison-Wesley Professional. 2001. ISBN 020170434.

[Sutter 2004] Sutter, Herb & Alexandrescu, Andrei. C++ Coding Standards: 101 Rules, Guidelines, and Best Practices. Addison-Wesley Professional. 2004. ISBN 0321113586.

[van Sprundel 2006] van Sprundel, Ilja. Unusual bugs. 2006.

[Viega 2003] Viega, John & Messier, Matt. Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Networking, Input Validation & More. O'Reilly. 2003. ISBN 0-596-00394-3.

[Viega 2005] Viega, John. CLASP Reference Guide, Volume 1.1. Secure Software. 2005.

[VU#159523] Giobbi, Ryan. Vulnerability Note VU#159523. Adobe Flash Player integer overflow vulnerability. April 2008.

[VU#162289] Dougherty, Chad. Vulnerability Note VU#162289. GCC Silently Discards Some Wraparound Checks. April 2008.

[VU#623332] Mead, Robert. Vulnerability Note VU#623332. MIT Kerberos 5 contains double free vulnerability in "krb5_recvauth()" function. July 2005.

[VU#925211] Weimer, Florian. Vulnerability Note VU#925211. Debian and Ubuntu OpenSSL packages contain a predictable random number generator. May 2008.

[Warren 2002] Warren, Henry S. Hacker's Delight. Addison Wesley Professional. 2002. ISBN 0201914654.

[Williams 2010a] Williams, Anthony. Thread. Boost Library. 2010.

[Williams 2010b] Williams, Anthony. Simpler Multithreading in C++0x. Internet.com. 2010.

[xorl 2009] xorl. xorl %eax, %eax. December 2016 [accessed].



15:59 | Impressed! | Voted(0) | Comment(0)
2019/03/25

ODR example

Tweet ThisSend to Facebook | by kaizen
// a.cpp
struct S {
  int a;
};
  
// b.cpp
class S {
public:
  int a;
};

// S.h
struct S {
  int a;
};
  
// a.cpp
#include "S.h"
  
// b.cpp
#include "S.h"

// a.cpp
namespace {
struct S {
  int a;
};
}
  
// b.cpp
namespace {
class S {
public:
  int a;
};
}

// s.h
struct S {
  char c;
  int a;
};
  
void init_s(S &s);
  
// s.cpp
#include "s.h"
  
void init_s(S &s); {
  s.c = 'a';
  s.a = 12;
}
  
// a.cpp
#pragma pack(push, 1)
#include "s.h"
#pragma pack(pop)
  
void f() {
  S s;
  init_s(s);
}

// s.h
struct S {
  char c;
  int a;
};
  
void init_s(S &s);
  
// s.cpp
#include "s.h"
  
void init_s(S &s); {
  s.c = 'a';
  s.a = 12;
}
  
// a.cpp
#include "s.h"
  
void f() {
  S s;
  init_s(s);
}


const int n = 42;
  
int g(const int &lhs, const int &rhs);
  
inline int f(int k) {
  return g(k, n);
}

const int n = 42;
  
int g(int lhs, int rhs);
  
inline int f(int k) {
  return g(k, n);
}

enum Constants {
  N = 42
};
 
int g(const int &lhs, const int &rhs);
  
inline int f(int k) {
  return g(k, N);
}



15:51 | Impressed! | Voted(0) | Comment(0)
2019/03/25

C++ one definition rule

Tweet ThisSend to Facebook | by kaizen

Nontrivial C++ programs are generally divided into multiple translation units that are later linked together to form an executable. To support such a model, C++ restricts named object definitions to ensure that linking will behave deterministically by requiring a single definition for an object across all translation units. This model is called the one-definition rule (ODR), which is defined by the C++ Standard, [basic.def.odr], in paragraph 4 [ISO/IEC 14882-2014]:

Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required. The definition can appear explicitly in the program, it can be found in the standard or a user-defined library, or (when appropriate) it is implicitly-defined. An inline function shall be defined in every translation unit in which it is odr-used.

The most common approach to multitranslation unit compilation involves declarations residing in a header file that is subsequently made available to a source file via #include. These declarations are often also definitions, such as class and function template definitions. This approach is allowed by an exception defined in paragraph 6, which, in part, states the following:

There can be more than one definition of a class type, enumeration type, inline function with external linkage, class template, non-static function template, static data member of a class template, member function of a class template, or template specialization for which some template parameters are not specified in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit....

If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.

The requirements specified by paragraph 6 essentially state that that two definitions must be identical (not simply equivalent). Consequently, a definition introduced in two separate translation units by an #include directive generally will not violate the ODR because the definitions are identical in both translation units.

However, it is possible to violate the ODR of a definition introduced via #include using block language linkage specifications, vendor-specific language extensions, and so on. A more likely scenario for ODR violations is that accidental definitions of differing objects will exist in different translation units.

Do not violate the one-definition rule; violations result in undefined behavior.

Noncompliant Code Example

In this noncompliant code example, two different translation units define a class of the same name with differing definitions. Although the two definitions are functionally equivalent (they both define a class named S with a single, public, nonstatic data member int a), they are not defined using the same sequence of tokens. This code example violates the ODR and results in undefined behavior.

Compliant Solution

The correct mitigation depends on programmer intent. If the programmer intends for the same class definition to be visible in both translation units because of common usage, the solution is to use a header file to introduce the object into both translation units, as shown in this compliant solution.

Compliant Solution

If the ODR violation was a result of accidental name collision, the best mitigation solution is to ensure that both class definitions are unique, as in this compliant solution.

Alternatively, the classes could be given distinct names in each translation unit to avoid violating the ODR.

Noncompliant Code Example (Microsoft Visual Studio)

In this noncompliant code example, a class definition is introduced into two translation units using #include. However, one of the translation units uses an implementation-defined #pragma that is supported by Microsoft Visual Studio to specify structure field alignment requirements. Consequently, the two class definitions may have differing layouts in each translation unit, which is a violation of the ODR.

Implementation Details

It is possible for the preceding noncompliant code example to result in a.cpp allocating space for an object with a different size than expected by init_s() in s.cpp. When translating s.cpp, the layout of the structure may include padding bytes between the c and a data members. When translating a.cpp, the layout of the structure may remove those padding bytes as a result of the #pragma pack directive, so the object passed to init_s() may be smaller than expected. Consequently, when init_s() initializes the data members of s, it may result in a buffer overrun.

For more information on the behavior of #pragma pack, see the vendor documentation for your implementation, such as Microsoft Visual Studio or GCC.

Compliant Solution

In this compliant solution, the implementation-defined structure member-alignment directive is removed, ensuring that all definitions of S comply with the ODR.

Noncompliant Code Example

In this noncompliant code example, the constant object n has internal linkage but is odr-usedwithin f(), which has external linkage. Because f() is declared as an inline function, the definition of f() must be identical in all translation units. However, each translation unit has a unique instance of n, resulting in a violation of the ODR.

Compliant Solution

A compliant solution must change one of three factors: (1) it must not odr-use n within f(), (2) it must declare n such that it has external linkage, or (3) it must not use an inline definition of f().

If circumstances allow modification of the signature of g() to accept parameters by value instead of by reference, then n will not be odr-used within f() because n would then qualify as a constant expression. This solution is compliant but it is not ideal. It may not be possible (or desirable) to modify the signature of g(), such as if g() represented std::max()from <algorithm>. Also, because of the differing linkage used by n and f(), accidental violations of the ODR are still likely if the definition of f() is modified to odr-use n.

Compliant Solution

In this compliant solution, the constant object n is replaced with an enumerator of the same name. Named enumerations defined at namespace scope have the same linkage as the namespace they are contained in. The global namespace has external linkage, so the definition of the named enumeration and its contained enumerators also have external linkage. Although less aesthetically pleasing, this compliant solution does not suffer from the same maintenance burdens of the previous code because n and f() have the same linkage.

Risk Assessment

Violating the ODR causes undefined behavior, which can result in exploits as well as denial-of-service attacks. As shown in "Support for Whole-Program Analysis and the Verification of the One-Definition Rule in C++" [Quinlan 06], failing to enforce the ODR enables a virtual function pointer attack known as the VPTR exploit. In this exploit, an object's virtual function table is corrupted so that calling a virtual function on the object results in malicious code being executed. See the paper by Quinlan and colleagues for more details. However, note that to introduce the malicious class, the attacker must have access to the system building the code.


15:43 | Impressed! | Voted(0) | Comment(0)
12345Next