Solid Sands: the day that GNU-C++ -Os broke

admin fyvrlbbjjswv , , , , , , ,

first_imgWe spent a good day of debugging a few of our C++ tests before a pattern emerged. We are working on a project to support freestanding C and C++ environments with the SuperTest test and validation suite for C and C++ compilers. A freestanding environment is defined to support only a subset of the C and C++ libraries. Its goal is to allow applications to run on targets that do not have an extensive run-time system like a proper OS. Instead, it allows programs to run on ‘bare-metal’. This is useful for all kinds of embedded applications.One of the goals in this project is to minimize the memory requirements of the SuperTest, so we use the compiler with the memory optimization option -Os .Several C++ tests, related to exception handling and inheritance, suddenly failed in the new freestanding configuration.When tests fail like this, the first thing to suspect is our own changes. After all, the compiler used is the default g++ compiler on a fully up-to-date x86 Ubuntu environment. Many thousands (millions?) of mission-critical systems use GNU-C++ and Ubuntu. Space-X, just to name a high-profile example, uses C++ and Linux on x86 in their rockets too.Here is one such test. Yes, we know this is not nice C++, but we are not in the business of writing nice C++. Our job is to go near the edge of the language specification to verify the correct behavior of its implementation.    #include    class A {            virtual void f(){};        public:            int x;            A(int in): x(in) {};    };    class B: public A {        public:            int y;            B(int in):A(in-1), y(in) {};    };    int test(void) {        int res;        B b(2);        A* bp = &b;        void* vp = dynamic_cast(bp);        if (  ((A*)vp)->x == 1           && ((B*)vp)->y == 2           ) {            return 1;   // PASS        } else {            return 0;   // FAIL        }    }    int main (void) {        assert (test ());    }The code is not complicated, but it has some unnecessary, though well-defined, type-casting. Class A is inherited by class B and both have their own instance variable, x and y respectively. The instantiation of an object of class B , in the second line of the function test , initializes these variables with the values 1 and 2 . After two type casts, the if statement verifies these values.Let us first admire the beauty of the x86-64 code generated by g++ for the function test() with the option -O1 :test():  mov DWORD PTR [rsp-8], 1  mov DWORD PTR [rsp-4], 2  mov rdx, QWORD PTR vtable for B[rip]  movabs rax, 8589934593  cmp QWORD PTR [rsp-8+rdx], rax  sete al  movzx eax, al  retA::f():  rep retThe compiler knows the layout of the object of type B . With the first two moves, it sets the values of the two variables x and y . Then it compares the values of object b ’s fields with the 64-bit immediate 8589934593 . In hexadecimal, this value is easier to understand: 0x200000001 . The compiler does two comparisons of 32-bit values in one 64-bit comparison! That is a clever move. So far so good.But now compile the code with -Os , for size optimization. The generated code becomes:test():  mov rdx, QWORD PTR vtable for B[rip]  mov DWORD PTR [rsp-8], 1  movabs rax, 8589934593  cmp QWORD PTR [rsp-8+rdx], rax  sete al  movzx eax, al  retDo you see what is missing? Somehow, the compiler has forgotten to initialize b ‘s variable y to 2 ! And thus our test-program fails at the assert.This is a serious error. Due to the optimization that turns two comparisons into one, the compiler ‘forgets’ that the y field of the object b is used. A def-use analysis after the optimization of the two comparisons then sees no use of y . Therefore the compiler concludes that the initialization of the field y is redundant, and removes it. Is this behavior limited to comparison optimization in combination with some liberal type-casting? Perhaps, but there is no guarantee for that.It is not the only error. There are also errors in the generated exception handling code when -Os is used. The version of GNU-C shown here is 7.3.0 because that is the current version on Ubuntu. We tried different versions of GNU-C, also for ARM64 targets and not Ubuntu related, and they are all affected. We must conclude that it is not safe to use g++ in combination with the -Os option for 64-bit targets.Compiler developers run many tests to prevent that errors like these slip through. But compilers are complicated and they have so many configuration options that no compiler supplier can state upfront that your particular use case is verified.If your application domain is mission-critical or even safety-critical, you need to set up compiler validation for the compiler and for the use cases that are specific to you. If that is beyond your scope, then at least verify that your compiler supplier uses SuperTest. SuperTest provides you with a better chance of staying ahead of compiler errors than any other method that we know of. Let’s hope that Space-X does not use g++ with the -Os option.Share this:TwitterFacebookLinkedInMoreRedditTumblrPinterestWhatsAppSkypePocketTelegram Tags: Tools & Software Continue Reading Previous FPGA-based frameworks speed blockchain processingNext Arm, Cadence and Xilinx introduce Arm Neoverse System Development Platformlast_img

You May Also Like..

Creating Compound Clips in FCPX

first_imgLearn how to create compound clips in this FCPX video tutorial.FCPX was designed with powerful organization and metadata features – one reason diehard FCPX video editors love it. FCPX allows you to create compound clips, “which allow you to  group any combination of clips in the Timeline or the Browser and nest clips within other clips”.There are a ton of really good uses for compound clips, from better organization to faster editing. Use them to break up a big timeline into manageable chunks. Give a compound clip unique settings (different from the overall project settings). In After Effects terms, you could think of compound clips as a nested sequence or a pre-composed composition.In the following tutorial we will take a look at how to use compound clips in your FCPX video editing workflow:Creating new compound clipsAdding clips to compound clipsUsing keyboard shortcutsAdjusting compound clip settingsUsing the timeline to create compound clipsWant to learn more about using compound clips in FCPX? Check out the official Apple documentation.How do you use compound clips? Share in the comments below.last_img

AAP to go it alone in Punjab

first_imgAam Aadmi Party convener and Delhi Chief Minister Arvind Kejriwal on Thursday ruled out any alliance in the upcoming parliamentary elections in Punjab, saying the party would contest all the 13 Lok Sabha seats alone.“The AAP will contest all the Lok Sabha seats in Punjab and will not enter into any tie-up with anyone,” Mr. Kejriwal said in Bathinda, where he had come to attend a marriage ceremony of a party legislator.Mr. Kejriwal hit out at the ruling Congress government in Punjab, accusing it of failing to keep its promises made during the Assembly elections in 2017. “Not a single promise made by Amarinder Singh has been fulfilled,” he alleged.“They (Congress) promised to eradicate the drug problem, but the menace still continues,” he said.‘No action’The Delhi Chief Minister also accused the Punjab government of failing to act against all those named in the Justice Ranjit Singh Commission’s inquiry report on incidents of religious sacrilege in the State.last_img

Tigers push series back home for KO match

first_imgPrivate companies step in to help SEA Games hosting Trending Articles PLAY LIST 00:50Trending Articles02:11’Not just basketball’: Circumcisions, pageants at Philippine courts00:50Trending Articles02:42PH underwater hockey team aims to make waves in SEA Games01:44Philippines marks anniversary of massacre with calls for justice01:19Fire erupts in Barangay Tatalon in Quezon City01:07Trump talks impeachment while meeting NCAA athletes02:49World-class track facilities installed at NCC for SEA Games02:11Trump awards medals to Jon Voight, Alison Krauss MOST READ Don’t miss out on the latest news and information. Panelo: Duterte ‘angry’ with SEA Games hosting hassles There’s just no quit in the Davao Occidental Tigers.Gritty and resilient, the South division champions sent the MPBL Datu Cup national finals to a winner-take-all Game 5 after hammering out a come-from-behind 77-66 victory over the San Juan Knights Monday night at Filoil Flying V Centre in San Juan.ADVERTISEMENT SEA Games hosting troubles anger Duterte Philippine Arena Interchange inaugurated DA eyes importing ‘galunggong’ anew Ex-pro Billy Ray Robles delivered a career performance with 22 points and 18 rebounds as the Tigers clawed their way back from a 10-point deficit early in the final period, before pulling away.“Everyone in the team believed and that’s all that mattered,” said Davao coach Don Dulay. “We needed to do whatever was possible to bring the series back home. Now we have Game 5 at home. It’s going to be wild.”FEATURED STORIESSPORTSPrivate companies step in to help SEA Games hostingSPORTSPalace wants Cayetano’s PHISGOC Foundation probed over corruption chargesSPORTSSingapore latest to raise issue on SEA Games food, logisticsThe deciding game of the series is slated on Thursday at Rizal Memorial College Gym in Davao City, where the Tigers won Game 2.“The crowd will be a big help and it would be nice to play in Davao, but definitely it still depends on us,” said Dulay. The Knights grabbed a 57-47 advantage a minute into the final period, but play was stopped for five minutes after a bottle of water was thrown on the floor.Sports Related Videospowered by AdSparcRead Next LATEST STORIES Duterte wants probe of SEA Games mess Hontiveros presses for security audit of national power grid Cayetano: Senate, Drilon to be blamed for SEA Games mess Down 2 goals, Ceres-Negros completes jaw-dropping turnaround vs Persija Jakarta View commentslast_img

Leave a Reply

Your email address will not be published. Required fields are marked *