blob: 5ecd0ba599e94f78f7b86d5507569bb7e316e761 [file] [log] [blame]
Alexei Frolove2016762019-11-14 13:49:52 -08001// Copyright 2019 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
Wyatt Hepler1a960942019-11-26 14:13:38 -08004// use this file except in compliance with the License. You may obtain a copy of
5// the License at
Alexei Frolove2016762019-11-14 13:49:52 -08006//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
Wyatt Hepler1a960942019-11-26 14:13:38 -080012// License for the specific language governing permissions and limitations under
13// the License.
Alexei Frolove2016762019-11-14 13:49:52 -080014
15#include "pw_bloat/bloat_this_binary.h"
16
17#include <cstring>
18
19namespace pw::bloat {
20
21char* volatile non_optimizable_pointer;
22
23void BloatThisBinary() {
Wyatt Heplercfe35262019-11-15 12:37:57 -080024 volatile unsigned counter = 0;
25
Alexei Frolove2016762019-11-14 13:49:52 -080026 // In case someone accidentally ends up flashing and running a bloat
Wyatt Heplercfe35262019-11-15 12:37:57 -080027 // executable on their device, loop forever instead of running this code.
Alexei Frolove2016762019-11-14 13:49:52 -080028 volatile bool clearly_false_condition = true;
Wyatt Heplercfe35262019-11-15 12:37:57 -080029 while (clearly_false_condition) {
30 counter += 1;
Alexei Frolove2016762019-11-14 13:49:52 -080031 }
32
33 // This code uses standard C/C++ functions such as memcpy to prevent them from
34 // showing up in size report deltas against a barebones base executable.
35 //
36 // This is done using garbage memory addresses as it consistently prevents the
37 // compiler from optimizing out parts of the code. Other approaches, such as a
38 // buffer, occasionally ran into optimization issues.
39 const char* s = "The quick brown fox jumps over the lazy dog.";
40
41 // Making the copy size large forces the compiler to generate a memcpy
42 // function instead of inlining it.
43 constexpr int kRandomLargeNumber = 2398;
44 std::memcpy(non_optimizable_pointer,
45 non_optimizable_pointer + std::strlen(s),
46 kRandomLargeNumber);
47
48 std::memmove(non_optimizable_pointer + 18,
49 non_optimizable_pointer,
50 kRandomLargeNumber);
51
52 *non_optimizable_pointer = std::strlen(non_optimizable_pointer);
53}
54
55} // namespace pw::bloat