From nobody Tue Feb 10 00:58:33 2026 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1659100198; cv=none; d=zohomail.com; s=zohoarc; b=K8FFZm2tNMKCFLLQD4z1WiTzkbI/1e2m5nmo19KBL+cWdQZjR09Y0lBhfmJiBA2FfKAG1UG42CcYc0Oxir6/CMlCtErEQucAv6KjRtOqlXZgVeuSQi883WL//3re9Fgcl2K3uwqorUYpt8XSaZNhOE4BN6nCqmg0Ub0VoFklY3k= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1659100198; h=Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=hlYPqOwXF8kEqxkm8xop27cvQNh7ZouuY1kfQAMVKXY=; b=U5P8HeVjAqCpuALCTaPhCa9+McSQYlAL6MmoBXHkhrqSfNFEnhFLTw440HbjEhBxR9AeOYemijlcQfalk1WlaO9fHoV4uh1w6frcDt6zZRGNvj67PVU55787reKHf9IsRUE58hcPd5M2vmfhxCwnddDbkiFJccBmJMSdMy2+AkI= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1659100198264449.59334643817215; Fri, 29 Jul 2022 06:09:58 -0700 (PDT) Received: from localhost ([::1]:49044 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1oHPkb-0005MN-5b for importer@patchew.org; Fri, 29 Jul 2022 09:09:57 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]:38558) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1oHPce-0007Q5-Ve for qemu-devel@nongnu.org; Fri, 29 Jul 2022 09:01:45 -0400 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]:37051) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1oHPcY-00008W-RL for qemu-devel@nongnu.org; Fri, 29 Jul 2022 09:01:44 -0400 Received: from mimecast-mx02.redhat.com (mimecast-mx02.redhat.com [66.187.233.88]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-533-NYTDOgrTNfuIYcfbwtKTrA-1; Fri, 29 Jul 2022 09:01:34 -0400 Received: from smtp.corp.redhat.com (int-mx04.intmail.prod.int.rdu2.redhat.com [10.11.54.4]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id 45970811E76; Fri, 29 Jul 2022 13:01:33 +0000 (UTC) Received: from localhost.localdomain (unknown [10.39.192.53]) by smtp.corp.redhat.com (Postfix) with ESMTP id 232482026D64; Fri, 29 Jul 2022 13:01:22 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1659099698; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=hlYPqOwXF8kEqxkm8xop27cvQNh7ZouuY1kfQAMVKXY=; b=fbLYysWkdIRF61kN8MsYtbjhg1NwUY3OrhpblMBMTLQJrMoCb/FzKe4a4PXJhn4USx3Mxb qH+u5p9z2J/00uOAY0Qs4qpvWtqvnlD/sa4zKOXBTr92OahB+uK+sdyUkJvri0ZZ942RPQ WoH13tzet0FmEbvaYJVZc6HQZC/9jgU= X-MC-Unique: NYTDOgrTNfuIYcfbwtKTrA-1 From: Alberto Faria To: qemu-devel@nongnu.org Cc: =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , Stefano Garzarella , Hannes Reinecke , "Dr. David Alan Gilbert" , Vladimir Sementsov-Ogievskiy , "Maciej S. Szmigiero" , Peter Lieven , kvm@vger.kernel.org, Xie Yongji , Eric Auger , Hanna Reitz , Jeff Cody , Eric Blake , "Denis V. Lunev" , =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= , =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Christian Schoenebeck , Stefan Weil , Klaus Jensen , Laurent Vivier , Alberto Garcia , Michael Roth , Juan Quintela , David Hildenbrand , qemu-block@nongnu.org, Konstantin Kostiuk , Kevin Wolf , Gerd Hoffmann , Stefan Hajnoczi , Marcelo Tosatti , Greg Kurz , "Michael S. Tsirkin" , Amit Shah , Paolo Bonzini , Alex Williamson , Peter Xu , Raphael Norwitz , Ronnie Sahlberg , Jason Wang , Emanuele Giuseppe Esposito , Richard Henderson , Marcel Apfelbaum , Dmitry Fleytman , Eduardo Habkost , Fam Zheng , Thomas Huth , Keith Busch , =?UTF-8?q?Alex=20Benn=C3=A9e?= , "Richard W.M. Jones" , John Snow , Markus Armbruster , Alberto Faria Subject: [RFC v2 03/10] static-analyzer: Support adding tests to checks Date: Fri, 29 Jul 2022 14:00:32 +0100 Message-Id: <20220729130040.1428779-4-afaria@redhat.com> In-Reply-To: <20220729130040.1428779-1-afaria@redhat.com> References: <20220729130040.1428779-1-afaria@redhat.com> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 2.78 on 10.11.54.4 Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=170.10.129.124; envelope-from=afaria@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -28 X-Spam_score: -2.9 X-Spam_bar: -- X-Spam_report: (-2.9 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.082, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_LOW=-0.7, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, T_SCC_BODY_TEXT_LINE=-0.01 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1659100200264100001 Content-Type: text/plain; charset="utf-8" Introduce an add_check_tests() method to add output-comparison tests to checks, and add some tests to the "return-value-never-used" check. Signed-off-by: Alberto Faria --- static-analyzer.py | 133 ++++++++++++++++++++- static_analyzer/__init__.py | 39 +++++- static_analyzer/return_value_never_used.py | 103 ++++++++++++++++ 3 files changed, 267 insertions(+), 8 deletions(-) diff --git a/static-analyzer.py b/static-analyzer.py index 3ade422dbf..16e331000d 100755 --- a/static-analyzer.py +++ b/static-analyzer.py @@ -11,17 +11,26 @@ import subprocess import sys import re -from argparse import ArgumentParser, Namespace, RawDescriptionHelpFormatter +from argparse import ( + Action, + ArgumentParser, + Namespace, + RawDescriptionHelpFormatter, +) from multiprocessing import Pool from pathlib import Path +from tempfile import TemporaryDirectory import textwrap import time +from traceback import print_exc from typing import ( + Callable, Iterable, Iterator, List, Mapping, NoReturn, + Optional, Sequence, Union, ) @@ -37,7 +46,7 @@ def parse_args() -> Namespace: =20 available_checks =3D "\n".join( - f" {name} {' '.join((CHECKS[name].__doc__ or '').split())}" + f" {name} {' '.join((CHECKS[name].checker.__doc__ or '').split(= ))}" for name in sorted(CHECKS) ) =20 @@ -134,14 +143,37 @@ def parse_args() -> Namespace: help=3D"Do everything except actually running the checks.", ) =20 + dev_options.add_argument( + "--test", + action=3DTestAction, + nargs=3D0, + help=3D"Run tests for all checks and exit.", + ) + # parse arguments =20 - args =3D parser.parse_args() + try: + args =3D parser.parse_args() + except TestSentinelError: + # --test was specified + if len(sys.argv) > 2: + parser.error("--test must be given alone") + return Namespace(test=3DTrue) + args.check_names =3D sorted(set(args.check_names or CHECKS)) =20 return args =20 =20 +class TestAction(Action): + def __call__(self, parser, namespace, values, option_string=3DNone): + raise TestSentinelError + + +class TestSentinelError(Exception): + pass + + # ------------------------------------------------------------------------= ---- # # Main =20 @@ -150,7 +182,11 @@ def main() -> int: =20 args =3D parse_args() =20 - if args.profile: + if args.test: + + return test() + + elif args.profile: =20 import cProfile import pstats @@ -170,6 +206,18 @@ def main() -> int: return analyze(args) =20 =20 +def test() -> int: + + for (check_name, check) in CHECKS.items(): + for group in check.test_groups: + for input in group.inputs: + run_test( + check_name, group.location, input, group.expected_outp= ut + ) + + return 0 + + def analyze(args: Namespace) -> int: =20 tr_units =3D get_translation_units(args) @@ -247,6 +295,7 @@ class TranslationUnit: build_command: str system_include_paths: Sequence[str] check_names: Sequence[str] + custom_printer: Optional[Callable[[str], None]] =20 =20 def get_translation_units(args: Namespace) -> Sequence["TranslationUnit"]: @@ -264,6 +313,7 @@ def get_translation_units(args: Namespace) -> Sequence[= "TranslationUnit"]: build_command=3Dcmd["command"], system_include_paths=3Dsystem_include_paths, check_names=3Dargs.check_names, + custom_printer=3DNone, ) for cmd in compile_commands ) @@ -380,7 +430,7 @@ def analyze_translation_unit(tr_unit: TranslationUnit) = -> bool: =20 try: for name in tr_unit.check_names: - CHECKS[name](check_context) + CHECKS[name].checker(check_context) except Exception as e: raise RuntimeError(f"Error analyzing {check_context._rel_path}") f= rom e =20 @@ -428,7 +478,9 @@ def get_check_context(tr_unit: TranslationUnit) -> Chec= kContext: except clang.cindex.TranslationUnitLoadError as e: raise RuntimeError(f"Failed to load {rel_path}") from e =20 - if sys.stdout.isatty(): + if tr_unit.custom_printer is not None: + printer =3D tr_unit.custom_printer + elif sys.stdout.isatty(): # add padding to fully overwrite progress message printer =3D lambda s: print(s.ljust(50)) else: @@ -457,6 +509,75 @@ def get_check_context(tr_unit: TranslationUnit) -> Che= ckContext: return check_context =20 =20 +# ------------------------------------------------------------------------= ---- # +# Tests + + +def run_test( + check_name: str, location: str, input: str, expected_output: str +) -> None: + + with TemporaryDirectory() as temp_dir: + + os.chdir(temp_dir) + + input_path =3D Path(temp_dir) / "file.c" + input_path.write_text(input) + + actual_output_list =3D [] + + tu_context =3D TranslationUnit( + absolute_path=3Dstr(input_path), + build_working_dir=3Dstr(input_path.parent), + build_command=3Df"cc {shlex.quote(str(input_path))}", + system_include_paths=3D[], + check_names=3D[check_name], + custom_printer=3Dlambda s: actual_output_list.append(s + "\n"), + ) + + check_context =3D get_check_context(tu_context) + + # analyze translation unit + + try: + + for name in tu_context.check_names: + CHECKS[name].checker(check_context) + + except Exception: + + print( + f"\033[0;31mTest defined at {location} raised an" + f" exception.\033[0m" + ) + print(f"\033[0;31mInput:\033[0m") + print(input, end=3D"") + print(f"\033[0;31mExpected output:\033[0m") + print(expected_output, end=3D"") + print(f"\033[0;31mException:\033[0m") + print_exc(file=3Dsys.stdout) + print(f"\033[0;31mAST:\033[0m") + check_context.print_tree(check_context.translation_unit.cursor) + + sys.exit(1) + + actual_output =3D "".join(actual_output_list) + + if actual_output !=3D expected_output: + + print(f"\033[0;33mTest defined at {location} failed.\033[0m") + print(f"\033[0;33mInput:\033[0m") + print(input, end=3D"") + print(f"\033[0;33mExpected output:\033[0m") + print(expected_output, end=3D"") + print(f"\033[0;33mActual output:\033[0m") + print(actual_output, end=3D"") + print(f"\033[0;33mAST:\033[0m") + check_context.print_tree(check_context.translation_unit.cursor) + + sys.exit(3) + + # ------------------------------------------------------------------------= ---- # # Utilities =20 diff --git a/static_analyzer/__init__.py b/static_analyzer/__init__.py index e6ca48d714..36028724b1 100644 --- a/static_analyzer/__init__.py +++ b/static_analyzer/__init__.py @@ -3,16 +3,20 @@ from ctypes import CFUNCTYPE, c_int, py_object from dataclasses import dataclass from enum import Enum +import inspect import os import os.path from pathlib import Path from importlib import import_module +import textwrap from typing import ( Any, Callable, Dict, + Iterable, List, Optional, + Sequence, Union, ) =20 @@ -218,18 +222,49 @@ def print_tree( =20 Checker =3D Callable[[CheckContext], None] =20 -CHECKS: Dict[str, Checker] =3D {} + +class CheckTestGroup: + + inputs: Sequence[str] + expected_output: str + + location: str + + def __init__(self, inputs: Iterable[str], expected_output: str) -> Non= e: + def reformat_string(s: str) -> str: + return "".join( + line + "\n" for line in textwrap.dedent(s).strip().splitli= nes() + ) + + self.inputs =3D [reformat_string(input) for input in inputs] + self.expected_output =3D reformat_string(expected_output) + + caller =3D inspect.stack()[1] + self.location =3D f"{os.path.relpath(caller.filename)}:{caller.lin= eno}" + + +@dataclass +class Check: + checker: Checker + test_groups: List[CheckTestGroup] + + +CHECKS: Dict[str, Check] =3D {} =20 =20 def check(name: str) -> Callable[[Checker], Checker]: def decorator(checker: Checker) -> Checker: assert name not in CHECKS - CHECKS[name] =3D checker + CHECKS[name] =3D Check(checker=3Dchecker, test_groups=3D[]) return checker =20 return decorator =20 =20 +def add_check_tests(check_name: str, *groups: CheckTestGroup) -> None: + CHECKS[check_name].test_groups.extend(groups) + + # ------------------------------------------------------------------------= ---- # # Import all checks =20 diff --git a/static_analyzer/return_value_never_used.py b/static_analyzer/r= eturn_value_never_used.py index 05c06cd4c2..de1a6542d1 100644 --- a/static_analyzer/return_value_never_used.py +++ b/static_analyzer/return_value_never_used.py @@ -11,7 +11,9 @@ =20 from static_analyzer import ( CheckContext, + CheckTestGroup, VisitorResult, + add_check_tests, check, might_have_attribute, visit, @@ -115,3 +117,104 @@ def get_parent_if_unexposed_expr(node: Cursor) -> Cur= sor: =20 =20 # ------------------------------------------------------------------------= ---- # + +add_check_tests( + "return-value-never-used", + CheckTestGroup( + inputs=3D[ + R""" + static void f(void) { } + """, + R""" + static __attribute__((unused)) int f(void) { } + """, + R""" + #define ATTR __attribute__((unused)) + static __attribute__((unused)) int f(void) { } + """, + R""" + #define FUNC static __attribute__((unused)) int f(void) { } + FUNC + """, + R""" + static __attribute__((unused, constructor)) int f(void) { } + """, + R""" + static __attribute__((constructor, unused)) int f(void) { } + """, + R""" + static int f(void) { return 42; } + static void g(void) { + int x =3D f(); + } + """, + R""" + static int f(void) { return 42; } + static void g(void) { + for (0; f(); 0) { } + } + """, + R""" + static int f(void) { return 42; } + static void g(void) { + for (f(); ; ) { } + } + """, + R""" + static int f(void) { return 42; } + static void g(void) { + for ( ; f(); ) { } + } + """, + R""" + static int f(void) { return 42; } + static void g(void) { + for ( ; ; f()) { } + } + """, + R""" + static int f(void) { return 42; } + static void g(void) { + int (*ptr)(void) =3D 0; + __atomic_store_n(&ptr, f, __ATOMIC_RELAXED); + } + """, + ], + expected_output=3DR""" + """, + ), + CheckTestGroup( + inputs=3D[ + R""" + static int f(void) { return 42; } + """, + R""" + static int f(void) { return 42; } + static void g(void) { + f(); + } + """, + R""" + static int f(void) { return 42; } + static void g(void) { + for (f(); 0; f()) { } + } + """, + ], + expected_output=3DR""" + file.c:1:12: f() return value is never used + """, + ), + CheckTestGroup( + inputs=3D[ + R""" + static __attribute__((constructor)) int f(void) { } + """, + ], + expected_output=3DR""" + file.c:1:41: f() return value is never used + """, + ), +) + +# ------------------------------------------------------------------------= ---- # --=20 2.37.1