Integrating Static Analysis into a Common Project Build Make Script

Some companies have internal Requirements for the style of C source codes.

Here are just a few points from a typical internal code-style:

  1. Function declarations must exactly match their definitions.

  2. Basic data types should not be used in source code, overrides should be used instead.

  3. All declarations and definitions of identifiers must be commented.

  4. There must be a default case at the end of the switch statement.

  5. All local variables of functions must be initialized before their first use.

  6. All function parameters must be listed 'in a column'

  7. There should be no 'magic numbers' in the source code

  8. There should be no tab characters in the source text.

  9. In complex expressions, parentheses must be used everywhere.

  10. For all declarations of global functions and variables in the h-file the keyword 'extern' is required.

  11. The line width must be no more than 80 characters.

  12. All macro parameters must be enclosed in parentheses.

  13. Functions without parameters must contain void in parentheses

  14. The body of the if, else if, switch, for, while, do..while constructs must be enclosed in curly braces.

  15. There should be no more than one definition per line.

  16. The source code must not contain commented code.

  17. All function parameters should have the 'const' specifier applied to them whenever possible.

  18. There should be no 'magic numbers' in the source code: all symbolic constants should have meaningful names

  19. and so on up to number 463

We even have a python script in our organization to automatically detect violations of the first 18 rules for formatting source code. I don't know who wrote it, but the script really works and finds some violations. About 10 percent of the total number of rules. At least something.

Statement of the problem

Make it so that along with the firmware build log, a text file also appears with a report on which internal standard rules were violated and indicate in which file and on which line in the source code these violations occurred.

What software do you need?

No.

Utility

appointment

1

autoverifier.py

utility for checking internal standard of program design

2

make

Software pipeline management utility

3

cat

print files to console

5

sed

console auto replace inside text files

6

python

phython language interpreter

7

cmd

console interpreter in windows

Implementation

I have a Python script autoverifier.py. If you run it by passing the absolute path to the source file, then a log will appear in stdout stating that the script has crashed.

However, a text file will appear in the directory from which this script was called. common_verifier_results.txt with a report on code style violations and compliance.

========C:\xxx\xxx\xxx\xxxx\xxxx\xxxx\xxx\xxx\i2s_drv.c========
  |      +  В исходном тексте не должно быть символов табуляции (СООТВЕТСТВУЕТ)
  |      +  Ширина строки должна быть не более 80 символов (СООТВЕТСТВУЕТ)
  |      +  Базовые типы данных не должны использоваться в исходном коде, вместо них – переопределения (СООТВЕТСТВУЕТ)
  |      +  Функции без параметров должны содержать в скобках void (СООТВЕТСТВУЕТ)
  |      +  Все параметры функций должны быть перечислены 'в столбик' (СООТВЕТСТВУЕТ)
  |      +  В конце оператора выбора switch должен быть default case (СООТВЕТСТВУЕТ)
  |      +  Тело конструкций if, else if, switch, for, while, do..while должно быть заключено в фигурные скобки (СООТВЕТСТВУЕТ)
  |      +  В одной строке должно быть не более одного определения (СООТВЕТСТВУЕТ)
  |      +  Исходный текст не должен содержать закомментированный код (СООТВЕТСТВУЕТ)
  |     --- В исходном коде не должно быть 'магических чисел': все символьные константы должны иметь осмысленные имена (НЕ СООТВЕТСТВУЕТ) (НЕ СООТВЕТСТВУЕТ)
  |       ->    В строке 753 обнаружено 'магическое число'
  |       ->    В строке 825 обнаружено 'магическое число'
  |       ->    В строке 915 обнаружено 'магическое число'
  |       ->    В строке 1435 обнаружено 'магическое число'
  |       ->    В строке 1494 обнаружено 'магическое число'
  |     --- Ко всем параметрам функций должен быть по возможности применен спецификатор 'const' (НЕ СООТВЕТСТВУЕТ)
  |       ->    В строке 1001 обнаружены аргументы ['Node'], к которым можно применить спецификатор 'const'
  |       ->    В строке 1053 обнаружены аргументы ['clockBus'], к которым можно применить спецификатор 'const'
  |      +  Все параметры макросов должны быть заключены в скобки (СООТВЕТСТВУЕТ)
  |     [WW] Для данного исходного файла не был найден соответсвующий ему заголовочный файл
  |     [WW] Для данного исходного файла не был найден соответсвующий ему заголовочный файл
  |      +  Объявления функций должны в точности соответствовать их определениям (СООТВЕТСТВУЕТ)
  |     --- Все объявления и определения идентификаторов должны быть прокомментированы (НЕ СООТВЕТСТВУЕТ)
  |       ->    В строке 187 идентификатор не прокомментирован
  |       ->    В строке 1401 идентификатор не прокомментирован
  |       ->    В строке 1461 идентификатор не прокомментирован
  |     --- В сложных выражениях везде должны стоять скобки (НЕ СООТВЕТСТВУЕТ)
  |       ->    В строке 708 обнаружено сложное выражение без достаточного количества скобок
  |       ->    В строке 753 обнаружено сложное выражение без достаточного количества скобок
  |      +  Все локальные переменные функций должны быть проинициализированы до первого использования (СООТВЕТСТВУЕТ)

As you can see with the + sign the script writes that it is good and with the – sign it writes that it is bad. If you call this script again only for another file, then the file common_verifier_results.txt will be rubbed through and the information will be lost.

Let me remind you that I need a full report for many files. In this regard, after each launch autoverifier.py dump log by file into a common text file.

At the same time, I am not interested in what is good. I am interested in what code-style points need to be corrected. Therefore, it is also necessary to automatically delete from the local report those lines that contain the plus symbol.

To summarize the above, we need to somehow assemble such a software conveyor.

The simplest solution is to use the GNU Make build system. This is what it looks like in make code.

$(info CodeStyleEhalScript)

include $(THIRD_PARTY_DIR)/code_style_files_to_check.mk

TOOLS_DIR = $(WORKSPACE_LOC)../tool
TOOLS_DIR := $(subst /cygdrive/c/,C:/, $(TOOLS_DIR))

AUTO_VERIFIER_DIR=$(TOOLS_DIR)/AutoVerifier/Software
AUTO_VERIFIER=$(AUTO_VERIFIER_DIR)/autoverifier.py


CODE_STYLE_TOOL = python $(AUTO_VERIFIER)
SOURCES_CODE_STYLE_CSC := $(subst .c,.ccs, $(SOURCES_CODE_STYLE_C))
SOURCES_CODE_STYLE_CSH := $(subst .h,.csh, $(SOURCES_CODE_STYLE_H))


#@echo $(error SOURCES_CODE_STYLE__CS= $(SOURCES_CODE_STYLE__CS))

CODE_STYLE_TOTAL_REPORT = $(BUILD_DIR)/$(TARGET)_code_style_report.txt

CODE_STYLE_ONE_REPORT=$(MK_PATH)common_verifier_results.txt

clean_report: $(SOURCES_CODE_STYLE_H)
	$(info RunCleanCodeStyleReport) 
	"" > $(CODE_STYLE_TOTAL_REPORT)


%.csh: %.h
	$(info RunCodeStyleCheck for H file) 
	rm -f $(CODE_STYLE_ONE_REPORT)
	$(CODE_STYLE_TOOL) $<
	sed -i '/ + /d' $(CODE_STYLE_ONE_REPORT)
	cat $(CODE_STYLE_ONE_REPORT) >> $(CODE_STYLE_TOTAL_REPORT)

%.ccs: %.c
	$(info RunCodeStyleCheck for C file) 
	rm -f $(CODE_STYLE_ONE_REPORT)
	$(CODE_STYLE_TOOL) $<
	sed -i '/ + /d' $(CODE_STYLE_ONE_REPORT)
	cat $(CODE_STYLE_ONE_REPORT) >> $(CODE_STYLE_TOTAL_REPORT)

.PHONY: code_style
code_style: $(SOURCES_CODE_STYLE_CSC) $(SOURCES_CODE_STYLE_CSH) 
	$(info CodeStyleCheckDone)

Just a few comments on the code…

Files to be analyzed can be explicitly specified in a separate make script code_style_files_to_check.mk

$(info AddFilesToCheckCodeStyle)

SOURCES_CODE_STYLE_C += $(THIRD_PARTY_DIR)/asics/nau8814/nau8814_driver.c
SOURCES_CODE_STYLE_H += $(THIRD_PARTY_DIR)/asics/nau8814/nau8814_driver.h
   ......
SOURCES_CODE_STYLE_C += $(THIRD_PARTY_DIR)/computing/dds/dds.c
SOURCES_CODE_STYLE_H += $(THIRD_PARTY_DIR)/computing/dds/dds.h
 

SOURCES_CODE_STYLE_H := $(subst /cygdrive/c/,C:/, $(SOURCES_CODE_STYLE_H))
SOURCES_CODE_STYLE_C := $(subst /cygdrive/c/,C:/, $(SOURCES_CODE_STYLE_C))

to delete all lines with the + symbol from a file, you need to do this

	sed -i '/ + /d' file.txt

I create imaginary extensions *.csh *.cсs only so that make guesses to run through all *.h *.c files. In fact, *.csh *.cсs are not files, but just text in the environment variable.

When the script is ready, it is enough to simply open the folder with the firmware project in the cmd console and execute the command

make -i code_style

After which, a file will appear in the folder with artifacts trunk\source\projects\config_name_m\build config_name_code_style_report.txt with a full report on violations of the internal standard for formatting source codes for those files that you listed in code_style_files_to_check.mk.

As you can see, the Make build system has once again done a favor. It turns out that through make scripts you can not only build *.bin(ari), but you can also add automatic generation of a report on the compliance of your internal code style to the build.

Who would have thought…

Results

It worked embed script for automatic detection of internal code-style violations directly into the main firmware build script.

The ability to mix all sorts of auxiliary actions into the firmware assembly is an excellent reason to assemble the code not from the GUI-IDE, but from self-written assembly scripts.

Links

Similar Posts

Leave a Reply

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