1/// 2/// Copyright (c) 2019 Arm Limited. 3/// 4/// SPDX-License-Identifier: MIT 5/// 6/// Permission is hereby granted, free of charge, to any person obtaining a copy 7/// of this software and associated documentation files (the "Software"), to 8/// deal in the Software without restriction, including without limitation the 9/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 10/// sell copies of the Software, and to permit persons to whom the Software is 11/// furnished to do so, subject to the following conditions: 12/// 13/// The above copyright notice and this permission notice shall be included in all 14/// copies or substantial portions of the Software. 15/// 16/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22/// SOFTWARE. 23/// 24namespace arm_compute 25{ 26/** 27@page contribution_guidelines Contribution guidelines 28 29@tableofcontents 30 31If you want to contribute to Arm Compute Library, be sure to review the following guidelines. 32 33The development is structured in the following way: 34- Release repository: https://github.com/arm-software/ComputeLibrary 35- Development repository: https://review.mlplatform.org/#/admin/projects/ml/ComputeLibrary 36- Please report issues here: https://github.com/ARM-software/ComputeLibrary/issues 37 38@section S5_1_coding_standards Coding standards and guidelines 39 40Best practices (as suggested by clang-tidy): 41 42- No uninitialised values 43 44Helps to prevent undefined behaviour and allows to declare variables const if they are not changed after initialisation. See http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-pro-type-member-init.html 45 46@code{.cpp} 47const float32x4_t foo = vdupq_n_f32(0.f); 48const float32x4_t bar = foo; 49 50const int32x4x2_t i_foo = {{ 51 vconvq_s32_f32(foo), 52 vconvq_s32_f32(foo) 53}}; 54const int32x4x2_t i_bar = i_foo; 55@endcode 56 57- No C-style casts (in C++ source code) 58 59Only use static_cast, dynamic_cast, and (if required) reinterpret_cast and const_cast. See http://en.cppreference.com/w/cpp/language/explicit_cast for more information when to use which type of cast. C-style casts do not differentiate between the different cast types and thus make it easy to violate type safety. Also, due to the prefix notation it is less clear which part of an expression is going to be casted. See http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-pro-type-cstyle-cast.html 60 61- No implicit casts to bool 62 63Helps to increase readability and might help to catch bugs during refactoring. See http://clang.llvm.org/extra/clang-tidy/checks/readability-implicit-bool-cast.html 64 65@code{.cpp} 66extern int *ptr; 67if(ptr){} // Bad 68if(ptr != nullptr) {} // Good 69 70extern int foo; 71if(foo) {} // Bad 72if(foo != 0) {} // Good 73@endcode 74 75- Use nullptr instead of NULL or 0 76 77The nullptr literal is type-checked and is therefore safer to use. See http://clang.llvm.org/extra/clang-tidy/checks/modernize-use-nullptr.html 78 79- No need to explicitly initialise std::string with an empty string 80 81The default constructor of std::string creates an empty string. In general it is therefore not necessary to specify it explicitly. See http://clang.llvm.org/extra/clang-tidy/checks/readability-redundant-string-init.html 82 83@code{.cpp} 84// Instead of 85std::string foo(""); 86std::string bar = ""; 87 88// The following has the same effect 89std::string foo; 90std::string bar; 91@endcode 92 93- Braces for all control blocks and loops (which have a body) 94 95To increase readability and protect against refactoring errors the body of control block and loops must be wrapped in braces. See http://clang.llvm.org/extra/clang-tidy/checks/readability-braces-around-statements.html 96 97For now loops for which the body is empty do not have to add empty braces. This exception might be revoked in the future. Anyway, situations in which this exception applies should be rare. 98 99@code{.cpp} 100Iterator it; 101while(it.next()); // No need for braces here 102 103// Make more use of it 104@endcode 105 106- Only one declaration per line 107 108Increase readability and thus prevent errors. 109 110@code{.cpp} 111int a, b; // BAD 112int c, *d; // EVEN WORSE 113 114int e = 0; // GOOD 115int *p = nullptr; // GOOD 116@endcode 117 118- Pass primitive types (and those that are cheap to copy or move) by value 119 120For primitive types it is more efficient to pass them by value instead of by const reference because: 121 122 - the data type might be smaller than the "reference type" 123 - pass by value avoids aliasing and thus allows for better optimisations 124 - pass by value is likely to avoid one level of indirection (references are often implemented as auto dereferenced pointers) 125 126This advice also applies to non-primitive types that have cheap copy or move operations and the function needs a local copy of the argument anyway. 127 128More information: 129 130 - http://stackoverflow.com/a/14013189 131 - http://stackoverflow.com/a/270435 132 - http://web.archive.org/web/20140113221447/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/ 133 134@code{.cpp} 135void foo(int i, long l, float32x4_t f); // Pass-by-value for builtin types 136void bar(const float32x4x4_t &f); // As this is a struct pass-by-const-reference is probably better 137void foobar(const MyLargeCustomTypeClass &m); // Definitely better as const-reference except if a copy has to be made anyway. 138@endcode 139 140- Don't use unions 141 142Unions cannot be used to convert values between different types because (in C++) it is undefined behaviour to read from a member other than the last one that has been assigned to. This limits the use of unions to a few corner cases and therefor the general advice is not to use unions. See http://releases.llvm.org/3.8.0/tools/clang/tools/extra/docs/clang-tidy/checks/cppcoreguidelines-pro-type-union-access.html 143 144- Use pre-increment/pre-decrement whenever possible 145 146In contrast to the pre-incerement the post-increment has to make a copy of the incremented object. This might not be a problem for primitive types like int but for class like objects that overload the operators, like iterators, it can have a huge impact on the performance. See http://stackoverflow.com/a/9205011 147 148To be consistent across the different cases the general advice is to use the pre-increment operator unless post-increment is explicitly required. The same rules apply for the decrement operator. 149 150@code{.cpp} 151for(size_t i = 0; i < 9; i++); // BAD 152for(size_t i = 0; i < 9; ++i); // GOOD 153@endcode 154 155- Don't use uint in C/C++ 156 157The C and C++ standards don't define a uint type. Though some compilers seem to support it by default it would require to include the header sys/types.h. Instead we use the slightly more verbose unsigned int type. 158 159- Don't use unsigned int in function's signature 160 161Unsigned integers are good for representing bitfields and modular arithmetic. The fact that unsigned arithmetic doesn't model the behavior of a simple integer, but is instead defined by the standard to model modular arithmetic (wrapping around on overflow/underflow), means that a significant class of bugs cannot be diagnosed by the compiler. Mixing signedness of integer types is responsible for an equally large class of problems. 162 163- No "Yoda-style" comparisons 164 165As compilers are now able to warn about accidental assignments if it is likely that the intention has been to compare values it is no longer required to place literals on the left-hand side of the comparison operator. Sticking to the natural order increases the readability and thus prevents logical errors (which cannot be spotted by the compiler). In the rare case that the desired result is to assign a value and check it the expression has to be surrounded by parentheses. 166 167@code{.cpp} 168if(nullptr == ptr || false == cond) // BAD 169{ 170 //... 171} 172 173if(ptr == nullptr || cond == false) // GOOD 174{ 175 //... 176} 177 178if(ptr = nullptr || cond = false) // Most likely a mistake. Will cause a compiler warning 179{ 180 //... 181} 182 183if((ptr = nullptr) || (cond = false)) // Trust me, I know what I'm doing. No warning. 184{ 185 //... 186} 187@endcode 188 189@subsection S5_1_1_rules Rules 190 191 - Use spaces for indentation and alignment. No tabs! Indentation should be done with 4 spaces. 192 - Unix line returns in all the files. 193 - Pointers and reference symbols attached to the variable name, not the type (i.e. char \&foo;, and not char& foo). 194 - No trailing spaces or tabs at the end of lines. 195 - No spaces or tabs on empty lines. 196 - Put { and } on a new line and increase the indentation level for code inside the scope (except for namespaces). 197 - Single space before and after comparison operators ==, <, >, !=. 198 - No space around parenthesis. 199 - No space before, one space after ; (unless it is at the end of a line). 200 201@code{.cpp} 202for(int i = 0; i < width * height; ++i) 203{ 204 void *d = foo(ptr, i, &addr); 205 static_cast<uint8_t *>(data)[i] = static_cast<uint8_t *>(d)[0]; 206} 207@endcode 208 209 - Put a comment after \#else, \#endif, and namespace closing brace indicating the related name 210 211@code{.cpp} 212namespace mali 213{ 214#ifdef MALI_DEBUG 215 ... 216#else // MALI_DEBUG 217 ... 218#endif // MALI_DEBUG 219} // namespace mali 220@endcode 221 222- CamelCase for class names only and lower case words separated with _ (snake_case) for all the functions / methods / variables / arguments / attributes. 223 224@code{.cpp} 225class ClassName 226{ 227 public: 228 void my_function(); 229 int my_attribute() const; // Accessor = attribute name minus '_', const if it's a simple type 230 private: 231 int _my_attribute; // '_' in front of name 232}; 233@endcode 234 235- Use quotes instead of angular brackets to include local headers. Use angular brackets for system headers. 236- Also include the module header first, then local headers, and lastly system headers. All groups should be separated by a blank line and sorted lexicographically within each group. 237- Where applicable the C++ version of system headers has to be included, e.g. cstddef instead of stddef.h. 238- See http://llvm.org/docs/CodingStandards.html#include-style 239 240@code{.cpp} 241#include "MyClass.h" 242 243#include "arm_cv/core/Helpers.h" 244#include "arm_cv/core/Types.h" 245 246#include <cstddef> 247#include <numeric> 248@endcode 249 250- Only use "auto" when the type can be explicitly deduced from the assignment. 251 252@code{.cpp} 253auto a = static_cast<float*>(bar); // OK: there is an explicit cast 254auto b = std::make_unique<Image>(foo); // OK: we can see it's going to be an std::unique_ptr<Image> 255auto c = img.ptr(); // NO: Can't tell what the type is without knowing the API. 256auto d = vdup_n_u8(0); // NO: It's not obvious what type this function returns. 257@endcode 258 259- OpenCL: 260 - Use __ in front of the memory types qualifiers and kernel: __kernel, __constant, __private, __global, __local. 261 - Indicate how the global workgroup size / offset / local workgroup size are being calculated. 262 263 - Doxygen: 264 265 - No '*' in front of argument names 266 - [in], [out] or [in,out] *in front* of arguments 267 - Skip a line between the description and params and between params and @return (If there is a return) 268 - Align params names and params descriptions (Using spaces), and with a single space between the widest column and the next one. 269 - Use an upper case at the beginning of the description 270 271@snippet arm_compute/runtime/NEON/functions/NEActivationLayer.h NEActivationLayer snippet 272 273@subsection S5_1_2_how_to_check_the_rules How to check the rules 274 275astyle (http://astyle.sourceforge.net/) and clang-format (https://clang.llvm.org/docs/ClangFormat.html) can check and help you apply some of these rules. 276 277@subsection S5_1_3_library_size_guidelines Library size: best practices and guidelines 278 279@subsubsection S5_1_3_1_template_suggestions Template suggestions 280 281When writing a new patch we should also have in mind the effect it will have in the final library size. We can try some of the following things: 282 283 - Place non-dependent template code in a different non-templated class/method 284 285@code{.cpp} 286template<typename T> 287class Foo 288{ 289public: 290 enum { v1, v2 }; 291 // ... 292}; 293@endcode 294 295 can be converted to: 296 297@code{.cpp} 298struct Foo_base 299{ 300 enum { v1, v2 }; 301 // ... 302}; 303 304template<typename T> 305class Foo : public Foo_base 306{ 307public: 308 // ... 309}; 310@endcode 311 312 - In some cases it's preferable to use runtime switches instead of template parameters 313 314 - Sometimes we can rewrite the code without templates and without any (significant) performance loss. Let's say that we've written a function where the only use of the templated argument is used for casting: 315 316@code{.cpp} 317template <typename T> 318void NETemplatedKernel::run(const Window &window) 319{ 320... 321 *(reinterpret_cast<T *>(out.ptr())) = *(reinterpret_cast<const T *>(in.ptr())); 322... 323} 324@endcode 325 326The above snippet can be transformed to: 327 328@code{.cpp} 329void NENonTemplatedKernel::run(const Window &window) 330{ 331... 332std::memcpy(out.ptr(), in.ptr(), element_size); 333... 334} 335@endcode 336 337@subsection S5_1_4_secure_coding_practices Secure coding practices 338 339@subsubsection S5_1_4_1_general_coding_practices General Coding Practices 340 341- **Use tested and approved managed code** rather than creating new unmanaged code for common tasks. 342- **Utilize locking to prevent multiple simultaneous requests** or use a synchronization mechanism to prevent race conditions. 343- **Protect shared variables and resources** from inappropriate concurrent access. 344- **Explicitly initialize all your variables and other data stores**, either during declaration or just before the first usage. 345- **In cases where the application must run with elevated privileges, raise privileges as late as possible, and drop them as soon as possible**. 346- **Avoid calculation errors** by understanding your programming language's underlying representation and how it interacts with numeric calculation. Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how your language handles numbers that are too large or too small for its underlying representation. 347- **Restrict users from generating new code** or altering existing code. 348 349 350@subsubsection S5_1_4_2_secure_coding_best_practices Secure Coding Best Practices 351 352- **Validate input**. Validate input from all untrusted data sources. Proper input validation can eliminate the vast majority of software vulnerabilities. Be suspicious of most external data sources, including command line arguments, network interfaces, environmental variables, and user controlled files. 353- **Heed compiler warnings**. Compile code using the default compiler flags that exist in the SConstruct file. 354- Use **static analysis tools** to detect and eliminate additional security flaws. 355- **Keep it simple**. Keep the design as simple and small as possible. Complex designs increase the likelihood that errors will be made in their implementation, configuration, and use. Additionally, the effort required to achieve an appropriate level of assurance increases dramatically as security mechanisms become more complex. 356- **Default deny**. Base access decisions on permission rather than exclusion. This means that, by default, access is denied and the protection scheme identifies conditions under which access is permitted 357- **Adhere to the principle of least privilege**. Every process should execute with the least set of privileges necessary to complete the job. Any elevated permission should only be accessed for the least amount of time required to complete the privileged task. This approach reduces the opportunities an attacker has to execute arbitrary code with elevated privileges. 358- **Sanitize data sent to other systems**. Sanitize all data passed to complex subsystems such as command shells, relational databases, and commercial off-the-shelf (COTS) components. Attackers may be able to invoke unused functionality in these components through the use of various injection attacks. This is not necessarily an input validation problem because the complex subsystem being invoked does not understand the context in which the call is made. Because the calling process understands the context, it is responsible for sanitizing the data before invoking the subsystem. 359- **Practice defense in depth**. Manage risk with multiple defensive strategies, so that if one layer of defense turns out to be inadequate, another layer of defense can prevent a security flaw from becoming an exploitable vulnerability and/or limit the consequences of a successful exploit. For example, combining secure programming techniques with secure runtime environments should reduce the likelihood that vulnerabilities remaining in the code at deployment time can be exploited in the operational environment. 360 361@subsection S5_1_5_guidelines_for_stable_api_abi Guidelines for stable API/ABI 362 363The Application Programming Interface (API) and Application Binary Interface (ABI) are the interfaces exposed 364to users so their programs can interact with the library efficiently and effectively. Even though changing API/ABI 365in a way that does not give backward compatibility is not necessarily bad if it can improve other users' experience and the library, 366contributions should be made with the awareness of API/ABI stability. If you'd like to make changes that affects 367the library's API/ABI, please review and follow the guidelines shown in this section. Also, please note that 368these guidelines are not exhaustive list but discussing things that might be easily overlooked. 369 370@subsubsection S5_1_5_1_guidelines_for_api Guidelines for API 371 372- When adding new arguments, consider grouping arguments (including the old ones) into a struct rather than adding arguments with default values. 373Introducing a new struct might break the API/ABI once, but it will be helpful to keep the stability. 374- When new member variables are added, please make sure they are initialized. 375- Avoid adding enum elements in the middle. 376- When removing arguments, follow the deprecation process described in the following section. 377- When changing behavior affecting API contracts, follow the deprecation process described in the following section. 378 379@subsubsection S5_1_5_2_guidelines_for_abi Guidelines for ABI 380 381We recommend to read through <a href="https://community.kde.org/Policies/Binary_Compatibility_Issues_With_C%2B%2B">this page</a> 382and double check your contributions to see if they include the changes listed. 383 384Also, for classes that requires strong ABI stability, consider using <a href="https://en.cppreference.com/w/cpp/language/pimpl">pImpl idiom</a>. 385 386@subsubsection S5_1_5_3_api_deprecation_process API deprecation process 387 388In order to deprecate an existing API, these rules should be followed. 389 390- Removal of a deprecated API should wait at least for one official release. 391- Deprecation of runtime APIs should strictly follow the aforementioned period, whereas core APIs can have more flexibility as they are mostly used internally rather than user-facing. 392- Any API changes (update, addition and deprecation) in all components should be well documented by the contribution itself. 393 394Also, it is recommended to use the following utility macros which is designed to work with both clang and gcc using C++11 and later. 395 396- ARM_COMPUTE_DEPRECATED: Just deprecate the wrapped function 397- ARM_COMPUTE_DEPRECATED_REL: Deprecate the wrapped function and also capture the release that was deprecated 398- ARM_COMPUTE_DEPRECATED_REL_REPLACE: Deprecate the wrapped function and also capture the release that was deprecated along with a possible replacement candidate 399 400@code{.cpp} 401ARM_COMPUTE_DEPRECATED_REL_REPLACE(20.08, DoNewThing) 402void DoOldThing(); 403 404void DoNewThing(); 405@endcode 406 407@section S5_2_how_to_submit_a_patch How to submit a patch 408 409To be able to submit a patch to our development repository you need to have a GitHub account. With that, you will be able to sign in to Gerrit where your patch will be reviewed. 410 411Next step is to clone the Compute Library repository: 412 413 git clone "ssh://<your-github-id>@review.mlplatform.org:29418/ml/ComputeLibrary" 414 415If you have cloned from GitHub or through HTTP, make sure you add a new git remote using SSH: 416 417 git remote add acl-gerrit "ssh://<your-github-id>@review.mlplatform.org:29418/ml/ComputeLibrary" 418 419After that, you will need to upload an SSH key to https://review.mlplatform.org/#/settings/ssh-keys 420 421Then, make sure to install the commit-msg Git hook in order to add a change-ID to the commit message of your patch: 422 423 cd "ComputeLibrary" && mkdir -p .git/hooks && curl -Lo `git rev-parse --git-dir`/hooks/commit-msg https://review.mlplatform.org/tools/hooks/commit-msg; chmod +x `git rev-parse --git-dir`/hooks/commit-msg) 424 425When your patch is ready, remember to sign off your contribution by adding a line with your name and e-mail address to every git commit message: 426 427 Signed-off-by: John Doe <john.doe@example.org> 428 429You must use your real name, no pseudonyms or anonymous contributions are accepted. 430 431You can add this to your patch with: 432 433 git commit -s --amend 434 435You are now ready to submit your patch for review: 436 437 git push acl-gerrit HEAD:refs/for/master 438 439@section S5_3_code_review Patch acceptance and code review 440 441Once a patch is uploaded for review, there is a pre-commit test that runs on a Jenkins server for continuos integration tests. In order to be merged a patch needs to: 442 443- get a "+1 Verified" from the pre-commit job 444- get a "+1 Comments-Addressed", in case of comments from reviewers the committer has to address them all. A comment is considered addressed when the first line of the reply contains the word "Done" 445- get a "+2" from a reviewer, that means the patch has the final approval 446 447At the moment, the Jenkins server is not publicly accessible and for security reasons patches submitted by non-whitelisted committers do not trigger the pre-commit tests. For this reason, one of the maintainers has to manually trigger the job. 448 449If the pre-commit test fails, the Jenkins job will post a comment on Gerrit with the details about the failure so that the committer will be able to reproduce the error and fix the issue, if any (sometimes there can be infrastructure issues, a test platform disconnecting for example, where the job needs to be retriggered). 450 451*/ 452} // namespace arm_compute 453