From 4fc4b5aab7d7ce708123f49a1738a770bd308797 Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Mon, 26 May 2025 18:02:49 +0200 Subject: [PATCH 1/6] fpga: Remove dead code Signed-off-by: Philipp Jungkamp --- fpga/lib/memory.cpp | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 fpga/lib/memory.cpp diff --git a/fpga/lib/memory.cpp b/fpga/lib/memory.cpp deleted file mode 100644 index 3a213a158..000000000 --- a/fpga/lib/memory.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* Memory managment. - * - * Author: Daniel Krebs - * SPDX-FileCopyrightText: 2017 Institute for Automation of Complex Power Systems, RWTH Aachen University - * SPDX-License-Identifier: Apache-2.0 - */ - -#include -#include - -#include - -using namespace villas; - -bool HostRam::free(void *addr, size_t length) { - return munmap(addr, length) == 0; -} - -void *HostRam::allocate(size_t length, int flags) { - const int mmap_flags = flags | MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT; - const int mmap_protection = PROT_READ | PROT_WRITE; - - return mmap(nullptr, length, mmap_protection, mmap_flags, 0, 0); -} From bf6ea2fd918cfcc73e4a1a67f5d4fa643b07f2d9 Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Tue, 27 May 2025 17:58:51 +0200 Subject: [PATCH 2/6] fpga: Remove unused broken unit test Signed-off-by: Philipp Jungkamp --- fpga/tests/unit/rtds2gpu.cpp | 332 ----------------------------------- 1 file changed, 332 deletions(-) delete mode 100644 fpga/tests/unit/rtds2gpu.cpp diff --git a/fpga/tests/unit/rtds2gpu.cpp b/fpga/tests/unit/rtds2gpu.cpp deleted file mode 100644 index b84d0cb12..000000000 --- a/fpga/tests/unit/rtds2gpu.cpp +++ /dev/null @@ -1,332 +0,0 @@ -/* FIFO unit test. - * - * Author: Daniel Krebs - * SPDX-FileCopyrightText: 2017 Daniel Krebs - * SPDX-License-Identifier: Apache-2.0 - */ - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "global.hpp" - -using namespace villas; - -static constexpr size_t SAMPLE_SIZE = 4; -static constexpr size_t SAMPLE_COUNT = 1; -static constexpr size_t FRAME_SIZE = SAMPLE_COUNT * SAMPLE_SIZE; - -static constexpr size_t DOORBELL_OFFSET = SAMPLE_COUNT; -static constexpr size_t DATA_OFFSET = 0; - -static void dumpMem(const uint32_t *addr, size_t len) { - const size_t bytesPerLine = 16; - const size_t lines = (len) / bytesPerLine + 1; - const uint8_t *buf = reinterpret_cast(addr); - - size_t bytesRead = 0; - - for (size_t line = 0; line < lines; line++) { - const unsigned base = line * bytesPerLine; - printf("0x%04x: ", base); - - for (size_t i = 0; i < bytesPerLine && bytesRead < len; i++) { - printf("0x%02x ", buf[base + i]); - bytesRead++; - } - puts(""); - } -} - -// cppcheck-suppress unknownMacro -Test(fpga, rtds2gpu_loopback_dma, .description = "Rtds2Gpu") { - auto logger = Log::get("unit-test:rtds2gpu"); - - for (auto &ip : state.cards.front()->ips) { - if (*ip != fpga::Vlnv("acs.eonerc.rwth-aachen.de:hls:rtds2gpu:")) - continue; - - logger->info("Testing {}", *ip); - - // Collect neccessary IPs - auto rtds2gpu = std::dynamic_pointer_cast(ip); - - auto axiSwitch = std::dynamic_pointer_cast( - state.cards.front()->lookupIp( - fpga::Vlnv("xilinx.com:ip:axis_switch:"))); - - auto dma = std::dynamic_pointer_cast( - state.cards.front()->lookupIp(fpga::Vlnv("xilinx.com:ip:axi_dma:"))); - - auto gpu2rtds = std::dynamic_pointer_cast( - state.cards.front()->lookupIp( - fpga::Vlnv("acs.eonerc.rwth-aachen.de:hls:gpu2rtds:"))); - - auto rtds = - std::dynamic_pointer_cast(state.cards.front()->lookupIp( - fpga::Vlnv("acs.eonerc.rwth-aachen.de:user:rtds_axis:"))); - - cr_assert_not_null(axiSwitch, "No AXI switch IP found"); - cr_assert_not_null(dma, "No DMA IP found"); - cr_assert_not_null(gpu2rtds, "No Gpu2Rtds IP found"); - cr_assert_not_null(rtds, "RTDS IP not found"); - - rtds2gpu.dump(spdlog::level::debug); - gpu2rtds->dump(spdlog::level::debug); - - // Allocate and prepare memory - - // Allocate space for all samples and doorbell register - auto dmaMemSrc = - HostDmaRam::getAllocator(0).allocate(SAMPLE_COUNT + 1); - auto dmaMemDst = - HostDmaRam::getAllocator(0).allocate(SAMPLE_COUNT + 1); - auto dmaMemDst2 = - HostDmaRam::getAllocator(0).allocate(SAMPLE_COUNT + 1); - - memset(&dmaMemSrc, 0x11, dmaMemSrc.getMemoryBlock().getSize()); - memset(&dmaMemDst, 0x55, dmaMemDst.getMemoryBlock().getSize()); - memset(&dmaMemDst2, 0x77, dmaMemDst2.getMemoryBlock().getSize()); - - const uint32_t *dataSrc = &dmaMemSrc[DATA_OFFSET]; - const uint32_t *dataDst = &dmaMemDst[DATA_OFFSET]; - const uint32_t *dataDst2 = &dmaMemDst2[0]; - - dumpMem(dataSrc, dmaMemSrc.getMemoryBlock().getSize()); - dumpMem(dataDst, dmaMemDst.getMemoryBlock().getSize()); - dumpMem(dataDst2, dmaMemDst2.getMemoryBlock().getSize()); - - // Connect AXI Stream from DMA to Rtds2Gpu IP - cr_assert(dma->connect(rtds2gpu)); - - cr_assert(rtds2gpu.startOnce(dmaMemDst.getMemoryBlock(), SAMPLE_COUNT, - DATA_OFFSET * 4, DOORBELL_OFFSET * 4), - "Preparing Rtds2Gpu IP failed"); - - cr_assert(dma->write(dmaMemSrc.getMemoryBlock(), FRAME_SIZE), - "Starting DMA MM2S transfer failed"); - - cr_assert(dma->writeComplete(), "DMA failed"); - - while (not rtds2gpu.isFinished()) - ; - - const uint32_t *doorbellDst = &dmaMemDst[DOORBELL_OFFSET]; - rtds2gpu.dump(spdlog::level::info); - rtds2gpu.dumpDoorbell(*doorbellDst); - - cr_assert(memcmp(dataSrc, dataDst, FRAME_SIZE) == 0, "Memory not equal"); - - for (size_t i = 0; i < SAMPLE_COUNT; i++) - gpu2rtds->registerFrames[i] = dmaMemDst[i]; - - // Connect AXI Stream from Gpu2Rtds IP to DMA - cr_assert(gpu2rtds->connect(*dma)); - - cr_assert(dma->read(dmaMemDst2.getMemoryBlock(), FRAME_SIZE), - "Starting DMA S2MM transfer failed"); - - cr_assert(gpu2rtds->startOnce(SAMPLE_COUNT), - "Preparing Gpu2Rtds IP failed"); - - cr_assert(dma->readComplete(), "DMA failed"); - - while (not gpu2rtds->isFinished()) - ; - - cr_assert(memcmp(dataSrc, dataDst2, FRAME_SIZE) == 0, "Memory not equal"); - - dumpMem(dataSrc, dmaMemSrc.getMemoryBlock().getSize()); - dumpMem(dataDst, dmaMemDst.getMemoryBlock().getSize()); - dumpMem(dataDst2, dmaMemDst2.getMemoryBlock().getSize()); - - logger->info(CLR_GRN("Passed")); - } -} - -// cppcheck-suppress unknownMacro -Test(fpga, rtds2gpu_rtt_cpu, .description = "Rtds2Gpu RTT via CPU") { - auto logger = Log::get("unit-test:rtds2gpu"); - - // Collect neccessary IPs - auto gpu2rtds = std::dynamic_pointer_cast( - state.cards.front()->lookupIp( - fpga::Vlnv("acs.eonerc.rwth-aachen.de:hls:gpu2rtds:"))); - - auto rtds2gpu = std::dynamic_pointer_cast( - state.cards.front()->lookupIp( - fpga::Vlnv("acs.eonerc.rwth-aachen.de:hls:rtds2gpu:"))); - - cr_assert_not_null(gpu2rtds, "No Gpu2Rtds IP found"); - cr_assert_not_null(rtds2gpu, "No Rtds2Gpu IP not found"); - - for (auto &ip : state.cards.front()->ips) { - if (*ip != fpga::Vlnv("acs.eonerc.rwth-aachen.de:user:rtds_axis:")) - continue; - - auto &rtds = dynamic_cast(*ip); - logger->info("Testing {}", rtds); - - auto dmaRam = - HostDmaRam::getAllocator().allocate(SAMPLE_COUNT + 1); - uint32_t *data = &dmaRam[DATA_OFFSET]; - uint32_t *doorbell = &dmaRam[DOORBELL_OFFSET]; - - // TEST: rtds loopback via switch, this should always work and have RTT=1 - //cr_assert(rtds.connect(rtds)); - //logger->info("loopback"); - //while (1); - - cr_assert(rtds.connect(*rtds2gpu)); - cr_assert(gpu2rtds->connect(rtds)); - - for (size_t i = 1; i <= 10000;) { - rtds2gpu->doorbellReset(*doorbell); - rtds2gpu->startOnce(dmaRam.getMemoryBlock(), SAMPLE_COUNT, - DATA_OFFSET * 4, DOORBELL_OFFSET * 4); - - // Wait by polling rtds2gpu IP or ... - // while (not rtds2gpu->isFinished()); - - // Wait by polling (local) doorbell register (= just memory) - while (not rtds2gpu->doorbellIsValid(*doorbell)) - ; - - // Copy samples to gpu2rtds IP - for (size_t i = 0; i < SAMPLE_COUNT; i++) { - gpu2rtds->registerFrames[i] = data[i]; - } - - // Waiting for gpu2rtds is not strictly required - gpu2rtds->startOnce(SAMPLE_COUNT); - //while (not gpu2rtds->isFinished()); - - if (i % 1000 == 0) { - logger->info("Successful iterations {}, data {}", i, data[0]); - rtds2gpu->dump(); - rtds2gpu->dumpDoorbell(data[1]); - } - } - - logger->info(CLR_GRN("Passed")); - } -} - -void gpu_rtds_rtt_start(volatile uint32_t *dataIn, - volatile reg_doorbell_t *doorbellIn, - volatile uint32_t *dataOut, - volatile fpga::ip::ControlRegister *controlRegister); - -void gpu_rtds_rtt_stop(); - -// cppcheck-suppress unknownMacro -Test(fpga, rtds2gpu_rtt_gpu, .description = "Rtds2Gpu RTT via GPU") { - auto logger = Log::get("unit-test:rtds2gpu"); - - // Collect neccessary IPs - auto gpu2rtds = std::dynamic_pointer_cast( - state.cards.front()->lookupIp( - fpga::Vlnv("acs.eonerc.rwth-aachen.de:hls:gpu2rtds:"))); - - auto rtds2gpu = std::dynamic_pointer_cast( - state.cards.front()->lookupIp( - fpga::Vlnv("acs.eonerc.rwth-aachen.de:hls:rtds2gpu:"))); - - cr_assert_not_null(gpu2rtds, "No Gpu2Rtds IP found"); - cr_assert_not_null(rtds2gpu, "No Rtds2Gpu IP not found"); - - auto gpuPlugin = Registry::lookup("cuda"); - cr_assert_not_null(gpuPlugin, "No GPU plugin found"); - - auto gpus = gpuPlugin->make(); - cr_assert(gpus.size() > 0, "No GPUs found"); - - // Just get first cpu - auto &gpu = gpus.front(); - - // Allocate memory on GPU and make accessible by to PCIe/FPGA - auto gpuRam = gpu->getAllocator().allocate(SAMPLE_COUNT + 1); - cr_assert(gpu->makeAccessibleToPCIeAndVA(gpuRam.getMemoryBlock())); - - // Make Gpu2Rtds IP register memory on FPGA accessible to GPU - cr_assert( - gpu->makeAccessibleFromPCIeOrHostRam(gpu2rtds->getRegisterMemory())); - - auto tr = gpu->translate(gpuRam.getMemoryBlock()); - - auto dataIn = reinterpret_cast( - tr.getLocalAddr(DATA_OFFSET * sizeof(uint32_t))); - auto doorbellIn = reinterpret_cast( - tr.getLocalAddr(DOORBELL_OFFSET * sizeof(uint32_t))); - - auto gpu2rtdsRegisters = gpu->translate(gpu2rtds->getRegisterMemory()); - - auto frameRegister = reinterpret_cast( - gpu2rtdsRegisters.getLocalAddr(gpu2rtds->registerFrameOffset)); - auto controlRegister = reinterpret_cast( - gpu2rtdsRegisters.getLocalAddr(gpu2rtds->registerControlAddr)); - - // auto doorbellInCpu = reinterpret_cast(&gpuRam[DOORBELL_OFFSET]); - - for (auto &ip : state.cards.front()->ips) { - if (*ip != fpga::Vlnv("acs.eonerc.rwth-aachen.de:user:rtds_axis:")) - continue; - - auto &rtds = dynamic_cast(*ip); - logger->info("Testing {}", rtds); - - // TEST: rtds loopback via switch, this should always work and have RTT=1 - //cr_assert(rtds.connect(rtds)); - //logger->info("loopback"); - //while (1); - - cr_assert(rtds.connect(*rtds2gpu)); - cr_assert(gpu2rtds->connect(rtds)); - - // Launch once so they are configured - cr_assert(rtds2gpu->startOnce(gpuRam.getMemoryBlock(), SAMPLE_COUNT, - DATA_OFFSET * 4, DOORBELL_OFFSET * 4)); - cr_assert(gpu2rtds->startOnce(SAMPLE_COUNT)); - - rtds2gpu->setAutoRestart(true); - rtds2gpu->start(); - - logger->info("GPU RTT RTDS"); - - std::string dummy; - - gpu_rtds_rtt_start(dataIn, doorbellIn, frameRegister, controlRegister); - - // while (1) { - // cr_assert(rtds2gpu->startOnce(gpuRam.getMemoryBlock(), SAMPLE_COUNT, DATA_OFFSET * 4, DOORBELL_OFFSET * 4)); - // } - - // for (int i = 0; i < 10000; i++) { - // while (not doorbellInCpu->is_valid); - // logger->debug("received data"); - // } - - // logger->info("Press enter to cancel"); - // std::cin >> dummy; - - while (1) { - sleep(1); - // logger->debug("Current sequence number: {}", doorbellInCpu->seq_nr); - logger->debug("Still running"); - } - - gpu_rtds_rtt_stop(); - - logger->info(CLR_GRN("Passed")); - } -} From cab6e02cedf654e59424fc4f7690f100d97df667 Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Tue, 27 May 2025 18:00:34 +0200 Subject: [PATCH 3/6] Introduce clang-tidy and fix diagnostics Signed-off-by: Philipp Jungkamp --- .clang-tidy | 10 +++ CMakeLists.txt | 8 +- clients/shmem/villas-shmem.cpp | 14 +-- common/include/villas/cpuset.hpp | 2 +- common/include/villas/dsp/window_cosine.hpp | 2 +- common/include/villas/exceptions.hpp | 6 +- common/include/villas/graph/directed.hpp | 2 +- .../include/villas/kernel/devices/driver.hpp | 1 + common/include/villas/kernel/vfio_device.hpp | 4 +- common/include/villas/memory.hpp | 16 ++-- common/include/villas/popen.hpp | 10 +-- common/include/villas/utils.hpp | 8 +- common/lib/dsp/pid.cpp | 10 +-- common/lib/hist.cpp | 12 +-- .../lib/kernel/devices/device_connection.cpp | 6 +- common/lib/kernel/devices/ip_device.cpp | 8 +- common/lib/kernel/devices/linux_driver.cpp | 2 +- common/lib/kernel/devices/pci_device.cpp | 46 +++++----- common/lib/kernel/devices/platform_device.cpp | 12 +-- common/lib/kernel/kernel.cpp | 33 +++---- common/lib/kernel/rt.cpp | 8 +- common/lib/kernel/vfio_container.cpp | 5 +- common/lib/kernel/vfio_device.cpp | 15 ++-- common/lib/memory.cpp | 5 +- common/lib/memory_manager.cpp | 6 +- common/lib/popen.cpp | 2 +- common/lib/table.cpp | 6 +- common/lib/task.cpp | 14 +-- common/lib/terminal.cpp | 4 +- common/lib/timing.cpp | 6 +- common/lib/tsc.cpp | 2 +- common/lib/utils.cpp | 6 +- common/lib/uuid.cpp | 2 +- common/tests/unit/buffer.cpp | 6 +- common/tests/unit/graph.cpp | 24 +++--- common/tests/unit/kernel.cpp | 4 +- common/tests/unit/list.cpp | 2 +- common/tests/unit/task.cpp | 9 +- common/tests/unit/timing.cpp | 42 ++++----- common/tests/unit/tsc.cpp | 10 ++- common/tests/unit/utils.cpp | 30 ++++--- fpga/include/villas/fpga/card_parser.hpp | 2 +- fpga/include/villas/fpga/core.hpp | 12 +-- fpga/include/villas/fpga/ips/aurora.hpp | 10 ++- .../include/villas/fpga/ips/aurora_xilinx.hpp | 4 +- fpga/include/villas/fpga/ips/axis_cache.hpp | 6 +- fpga/include/villas/fpga/ips/bram.hpp | 16 ++-- fpga/include/villas/fpga/ips/dino.hpp | 30 +++---- fpga/include/villas/fpga/ips/dma.hpp | 16 ++-- fpga/include/villas/fpga/ips/emc.hpp | 4 +- fpga/include/villas/fpga/ips/fifo.hpp | 6 +- fpga/include/villas/fpga/ips/gpio.hpp | 4 +- fpga/include/villas/fpga/ips/gpu2rtds.hpp | 4 +- fpga/include/villas/fpga/ips/hls.hpp | 4 +- fpga/include/villas/fpga/ips/i2c.hpp | 24 +++--- fpga/include/villas/fpga/ips/intc.hpp | 8 +- fpga/include/villas/fpga/ips/pcie.hpp | 22 ++--- fpga/include/villas/fpga/ips/register.hpp | 6 +- fpga/include/villas/fpga/ips/rtds.hpp | 10 ++- fpga/include/villas/fpga/ips/rtds2gpu.hpp | 8 +- fpga/include/villas/fpga/ips/switch.hpp | 16 ++-- fpga/include/villas/fpga/ips/timer.hpp | 4 +- fpga/include/villas/fpga/ips/zynq.hpp | 12 +-- fpga/include/villas/fpga/json_parser.hpp | 8 +- fpga/include/villas/fpga/node.hpp | 10 +-- fpga/include/villas/fpga/pcie_card.hpp | 8 +- fpga/include/villas/fpga/platform_card.hpp | 2 +- fpga/include/villas/fpga/utils.hpp | 6 +- fpga/lib/card.cpp | 9 +- fpga/lib/core.cpp | 18 ++-- fpga/lib/core_connection.cpp | 6 +- fpga/lib/dma.cpp | 17 ++-- fpga/lib/ips/bram.cpp | 2 +- fpga/lib/ips/dino.cpp | 9 +- fpga/lib/ips/dma.cpp | 16 ++-- fpga/lib/ips/emc.cpp | 2 +- fpga/lib/ips/i2c.cpp | 18 ++-- fpga/lib/ips/intc.cpp | 13 +-- fpga/lib/ips/pcie.cpp | 6 +- fpga/lib/ips/rtds2gpu/gpu2rtds.cpp | 2 +- fpga/lib/ips/timer.cpp | 3 +- fpga/lib/node.cpp | 2 +- fpga/lib/pcie_card.cpp | 2 +- fpga/lib/platform_card.cpp | 4 +- fpga/lib/utils.cpp | 2 +- fpga/src/villas-fpga-ctrl.cpp | 8 +- fpga/src/villas-fpga-pipe.cpp | 4 +- fpga/tests/unit/dma.cpp | 6 +- fpga/tests/unit/logging.cpp | 2 +- fpga/tests/unit/rtds.cpp | 4 +- fpga/tests/unit/rtds_rtt.cpp | 81 ----------------- include/villas/api.hpp | 4 +- include/villas/api/request.hpp | 10 +-- include/villas/api/response.hpp | 4 +- include/villas/format.hpp | 8 +- include/villas/formats/villas_binary.hpp | 2 +- include/villas/hook.hpp | 24 +++--- include/villas/hooks/lua.hpp | 4 +- include/villas/node.hpp | 14 +-- include/villas/node_compat.hpp | 2 +- include/villas/nodes/comedi.hpp | 1 + include/villas/nodes/example.hpp | 2 +- include/villas/nodes/exec.hpp | 2 +- include/villas/nodes/fpga.hpp | 4 +- include/villas/nodes/iec60870.hpp | 2 +- include/villas/nodes/iec61850_goose.hpp | 2 +- include/villas/nodes/loopback.hpp | 2 +- include/villas/nodes/loopback_internal.hpp | 2 +- include/villas/nodes/modbus.hpp | 2 +- include/villas/nodes/mqtt.hpp | 2 + include/villas/nodes/ngsi.hpp | 1 + include/villas/nodes/opendss.hpp | 2 +- include/villas/nodes/temper.hpp | 10 +-- include/villas/nodes/test_rtt.hpp | 2 +- include/villas/nodes/webrtc.hpp | 2 +- include/villas/path_source.hpp | 2 +- include/villas/queue.hpp | 6 +- include/villas/signal_list.hpp | 2 +- include/villas/usb.hpp | 4 +- lib/api/requests/graph.cpp | 2 +- lib/api/requests/node_action.cpp | 2 +- lib/api/requests/node_file.cpp | 6 +- lib/api/requests/restart.cpp | 14 ++- lib/api/requests/status.cpp | 2 +- lib/api/requests/universal.cpp | 2 +- lib/config.cpp | 10 ++- lib/config_helper.cpp | 14 ++- lib/dumper.cpp | 7 +- lib/formats/json.cpp | 4 +- lib/formats/json_kafka.cpp | 6 +- lib/formats/msg.cpp | 2 +- lib/formats/opal_asyncip.cpp | 2 +- lib/formats/protobuf.cpp | 4 +- lib/formats/raw.cpp | 6 +- lib/formats/villas_human.cpp | 2 +- lib/hook.cpp | 2 +- lib/hook_list.cpp | 2 +- lib/hooks/average.cpp | 2 +- lib/hooks/digest.cpp | 6 +- lib/hooks/dp.cpp | 22 ++--- lib/hooks/drop.cpp | 6 +- lib/hooks/ebm.cpp | 4 +- lib/hooks/fix.cpp | 2 +- lib/hooks/frame.cpp | 6 +- lib/hooks/gate.cpp | 2 +- lib/hooks/jitter_calc.cpp | 2 +- lib/hooks/lua.cpp | 86 ++----------------- lib/hooks/ma.cpp | 5 +- lib/hooks/pmu.cpp | 9 +- lib/hooks/pmu_dft.cpp | 60 ++++++------- lib/hooks/pmu_ipdft.cpp | 15 ++-- lib/hooks/power.cpp | 18 ++-- lib/hooks/pps_ts.cpp | 20 +++-- lib/hooks/print.cpp | 6 +- lib/hooks/reorder_ts.cpp | 13 ++- lib/hooks/restart.cpp | 4 +- lib/hooks/rms.cpp | 4 +- lib/hooks/skip_first.cpp | 4 +- lib/hooks/stats.cpp | 20 ++--- lib/kernel/if.cpp | 6 +- lib/kernel/tc_netem.cpp | 14 +-- lib/mapping.cpp | 4 +- lib/memory.cpp | 2 +- lib/memory/managed.cpp | 4 +- lib/node.cpp | 8 +- lib/node_compat.cpp | 10 +-- lib/node_direction.cpp | 14 +-- lib/nodes/amqp.cpp | 6 +- lib/nodes/can.cpp | 14 ++- lib/nodes/comedi.cpp | 15 ++-- lib/nodes/ethercat.cpp | 6 +- lib/nodes/example.cpp | 4 +- lib/nodes/exec.cpp | 4 +- lib/nodes/file.cpp | 7 +- lib/nodes/fpga.cpp | 4 +- lib/nodes/iec60870.cpp | 23 +++-- lib/nodes/iec61850_goose.cpp | 38 ++++---- lib/nodes/iec61850_sv.cpp | 13 +-- lib/nodes/infiniband.cpp | 52 ++++++----- lib/nodes/influxdb.cpp | 2 +- lib/nodes/kafka.cpp | 2 +- lib/nodes/loopback.cpp | 4 +- lib/nodes/loopback_internal.cpp | 2 +- lib/nodes/modbus.cpp | 28 +++--- lib/nodes/mqtt.cpp | 2 +- lib/nodes/nanomsg.cpp | 4 +- lib/nodes/ngsi.cpp | 10 +-- lib/nodes/opendss.cpp | 7 +- lib/nodes/redis.cpp | 9 +- lib/nodes/rtp.cpp | 8 +- lib/nodes/shmem.cpp | 2 +- lib/nodes/signal.cpp | 11 +-- lib/nodes/signal_v1.cpp | 8 +- lib/nodes/socket.cpp | 2 +- lib/nodes/stats.cpp | 4 +- lib/nodes/temper.cpp | 23 +++-- lib/nodes/test_rtt.cpp | 21 +++-- lib/nodes/uldaq.cpp | 18 ++-- lib/nodes/webrtc.cpp | 14 +-- lib/nodes/webrtc/peer_connection.cpp | 2 +- lib/nodes/webrtc/signaling_message.cpp | 9 +- lib/nodes/websocket.cpp | 24 +++--- lib/nodes/zeromq.cpp | 10 +-- lib/path.cpp | 16 ++-- lib/path_source.cpp | 4 +- lib/queue_signalled.cpp | 18 ++-- lib/sample.cpp | 12 +-- lib/shmem.cpp | 4 +- lib/web.cpp | 4 +- plugins/example_hook.cpp | 2 +- src/villas-compare.cpp | 8 +- src/villas-conf2json.cpp | 11 ++- src/villas-convert.cpp | 8 +- src/villas-graph.cpp | 8 +- src/villas-hook.cpp | 12 +-- src/villas-node.cpp | 8 +- src/villas-pipe.cpp | 23 ++--- src/villas-relay.cpp | 2 +- src/villas-relay.hpp | 10 ++- src/villas-signal.cpp | 8 +- src/villas-test-config.cpp | 6 +- src/villas-zmq-keygen.cpp | 2 +- tests/unit/config.cpp | 24 +++--- tests/unit/format.cpp | 19 ++-- tests/unit/queue.cpp | 12 +-- 225 files changed, 1047 insertions(+), 1095 deletions(-) create mode 100644 .clang-tidy delete mode 100644 fpga/tests/unit/rtds_rtt.cpp diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 000000000..ee12d4011 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: 2025 Institute for Automation of Complex Power Systems, RWTH Aachen University +# SPDX-License-Identifier: Apache-2.0 + +Checks: > + -*, + modernize-use-override, + misc-const-correctness, +WarningsAsErrors: '*' +HeaderFilterRegex: villas/.* +FormatStyle: file diff --git a/CMakeLists.txt b/CMakeLists.txt index ced886b62..1198fbd39 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -53,7 +53,13 @@ include(FindSymbol) include(CMakeDependentOption) add_definitions(-D_POSIX_C_SOURCE=200809L -D_GNU_SOURCE) -add_compile_options(-Wall -Wno-unknown-pragmas -fdiagnostics-color=auto) +add_compile_options( + -Wall + -Wno-unknown-pragmas + -Wno-vla-cxx-extension + -Wno-unused-command-line-argument + -fdiagnostics-color=auto +) # Check OS check_include_file("sys/eventfd.h" HAS_EVENTFD) diff --git a/clients/shmem/villas-shmem.cpp b/clients/shmem/villas-shmem.cpp index 0f2f05ca2..54acaf99e 100644 --- a/clients/shmem/villas-shmem.cpp +++ b/clients/shmem/villas-shmem.cpp @@ -34,7 +34,7 @@ class Shmem : public Tool { protected: std::atomic stop; - void usage() { + void usage() override { std::cout << "Usage: villas-test-shmem WNAME VECTORIZE" << std::endl << " WNAME name of the shared memory object for the output queue" @@ -47,9 +47,9 @@ class Shmem : public Tool { printCopyright(); } - void handler(int, siginfo_t *, void *) { stop = true; } + void handler(int, siginfo_t *, void *) override { stop = true; } - int main() { + int main() override { int ret, readcnt, writecnt, avail; struct ShmemInterface shm; @@ -62,9 +62,9 @@ class Shmem : public Tool { return 1; } - std::string wname = argv[1]; - std::string rname = argv[2]; - int vectorize = atoi(argv[3]); + std::string const wname = argv[1]; + std::string const rname = argv[2]; + int const vectorize = atoi(argv[3]); ret = shmem_int_open(wname.c_str(), rname.c_str(), &shm, &conf); if (ret < 0) @@ -87,7 +87,7 @@ class Shmem : public Tool { outsmps[i]->sequence = insmps[i]->sequence; outsmps[i]->ts = insmps[i]->ts; - int len = MIN(insmps[i]->length, outsmps[i]->capacity); + int const len = MIN(insmps[i]->length, outsmps[i]->capacity); memcpy(outsmps[i]->data, insmps[i]->data, SAMPLE_DATA_LENGTH(len)); outsmps[i]->length = len; diff --git a/common/include/villas/cpuset.hpp b/common/include/villas/cpuset.hpp index 5b8d02fba..8411d7ebb 100644 --- a/common/include/villas/cpuset.hpp +++ b/common/include/villas/cpuset.hpp @@ -75,7 +75,7 @@ class CpuSet { size_t size() const { return sz; } CpuSet operator~() { - CpuSet full = UINTMAX_MAX; + CpuSet const full = UINTMAX_MAX; return full ^ *this; } diff --git a/common/include/villas/dsp/window_cosine.hpp b/common/include/villas/dsp/window_cosine.hpp index aedfa478e..1864dd8c2 100644 --- a/common/include/villas/dsp/window_cosine.hpp +++ b/common/include/villas/dsp/window_cosine.hpp @@ -27,7 +27,7 @@ class CosineWindow : public Window { T correctionFactor; - virtual T filter(T in, size_type i) const { return in * coefficients[i]; } + T filter(T in, size_type i) const override { return in * coefficients[i]; } public: CosineWindow(double a0, double a1, double a2, double a3, double a4, diff --git a/common/include/villas/exceptions.hpp b/common/include/villas/exceptions.hpp index e910dacd2..7e6b8e232 100644 --- a/common/include/villas/exceptions.hpp +++ b/common/include/villas/exceptions.hpp @@ -92,7 +92,7 @@ class ConfigError : public std::runtime_error { } public: - ~ConfigError() { + ~ConfigError() override { if (msg) free(msg); } @@ -132,12 +132,12 @@ class ConfigError : public std::runtime_error { } std::string docUri() const { - std::string baseUri = "https://villas.fein-aachen.org/doc/jump?"; + std::string const baseUri = "https://villas.fein-aachen.org/doc/jump?"; return baseUri + id; } - virtual const char *what() const noexcept { return msg; } + const char *what() const noexcept override { return msg; } }; } // namespace villas diff --git a/common/include/villas/graph/directed.hpp b/common/include/villas/graph/directed.hpp index 9b4ea8328..5a0bb93e6 100644 --- a/common/include/villas/graph/directed.hpp +++ b/common/include/villas/graph/directed.hpp @@ -100,7 +100,7 @@ class DirectedGraph { EdgeIdentifier addDefaultEdge(VertexIdentifier fromVertexId, VertexIdentifier toVertexId) { // Create a new edge - std::shared_ptr edge(new EdgeType); + std::shared_ptr const edge(new EdgeType); return addEdge(edge, fromVertexId, toVertexId); } diff --git a/common/include/villas/kernel/devices/driver.hpp b/common/include/villas/kernel/devices/driver.hpp index e156af96a..2d1862b23 100644 --- a/common/include/villas/kernel/devices/driver.hpp +++ b/common/include/villas/kernel/devices/driver.hpp @@ -24,6 +24,7 @@ class Driver { virtual std::string name() const = 0; virtual void override(const Device &device) const = 0; virtual void unbind(const Device &device) const = 0; + virtual ~Driver() {} }; } // namespace devices diff --git a/common/include/villas/kernel/vfio_device.hpp b/common/include/villas/kernel/vfio_device.hpp index 9aaa645fe..5aa27f13a 100644 --- a/common/include/villas/kernel/vfio_device.hpp +++ b/common/include/villas/kernel/vfio_device.hpp @@ -11,8 +11,6 @@ #pragma once -#include -#include #include #include @@ -99,7 +97,7 @@ class Device { std::vector mappings; // libpci handle of the device - const kernel::devices::PciDevice *pci_device; + [[maybe_unused]] const kernel::devices::PciDevice *pci_device; Logger log; }; diff --git a/common/include/villas/memory.hpp b/common/include/villas/memory.hpp index 922eb516d..c3dfad0cb 100644 --- a/common/include/villas/memory.hpp +++ b/common/include/villas/memory.hpp @@ -116,7 +116,8 @@ template class BaseAllocator { : memoryAddrSpaceId(memoryAddrSpaceId) { // CRTP derivedAlloc = static_cast(this); - std::string loggerName = fmt::format("memory:", derivedAlloc->getName()); + std::string const loggerName = + fmt::format("memory:", derivedAlloc->getName()); logger = Log::get(loggerName); // Default deallocation callback @@ -136,7 +137,6 @@ template class BaseAllocator { } virtual std::unique_ptr - allocateBlock(size_t size) = 0; template MemoryAccessor allocate(size_t num) { @@ -152,7 +152,7 @@ template class BaseAllocator { // Check if the allocated memory is really accessible by writing to the // allocated memory and reading back. Exponentially increase offset to // speed up testing. - MemoryAccessor byteAccessor(*mem); + MemoryAccessor const byteAccessor(*mem); size_t idx = 0; for (int i = 0; idx < mem->getSize(); i++, idx = (1 << i)) { auto val = static_cast(i); @@ -166,6 +166,8 @@ template class BaseAllocator { return MemoryAccessor(std::move(mem)); } + virtual ~BaseAllocator() {} + protected: void insertMemoryBlock(const MemoryBlock &mem) { auto &mm = MemoryManager::get(); @@ -217,8 +219,8 @@ class LinearAllocator : public BaseAllocator { std::string getName() const; - virtual std::unique_ptr - allocateBlock(size_t size); + std::unique_ptr + allocateBlock(size_t size) override; private: static constexpr size_t alignBytes = sizeof(uintptr_t); @@ -247,7 +249,7 @@ class HostRam { std::string getName() const { return "HostRamAlloc"; } std::unique_ptr - allocateBlock(size_t size); + allocateBlock(size_t size) override; }; static HostRamAllocator &getAllocator() { @@ -264,7 +266,7 @@ class HostDmaRam { public: HostDmaRamAllocator(int num); - virtual ~HostDmaRamAllocator(); + ~HostDmaRamAllocator() override; std::string getName() const { return getUdmaBufName(num); } diff --git a/common/include/villas/popen.hpp b/common/include/villas/popen.hpp index 95994f59d..b17e84bab 100644 --- a/common/include/villas/popen.hpp +++ b/common/include/villas/popen.hpp @@ -67,6 +67,11 @@ class PopenStream : public Popen { std::ostream &cout() { return *(output.stream); } + template + friend std::istream &operator>>(PopenStream &po, T &value) { + return *(po.input.stream) >> value; + } + void open(); int close(); @@ -84,8 +89,3 @@ class PopenStream : public Popen { } // namespace utils } // namespace villas - -template -std::istream &operator>>(villas::utils::PopenStream &po, T &value) { - return *(po.input.stream) >> value; -} diff --git a/common/include/villas/utils.hpp b/common/include/villas/utils.hpp index ce6defa42..826a28c49 100644 --- a/common/include/villas/utils.hpp +++ b/common/include/villas/utils.hpp @@ -81,8 +81,8 @@ #endif #define MAX(a, b) \ ({ \ - __typeof__(a) _a = (a); \ - __typeof__(b) _b = (b); \ + __typeof__(a) const &_a = (a); \ + __typeof__(b) const &_b = (b); \ _a > _b ? _a : _b; \ }) @@ -92,8 +92,8 @@ #endif #define MIN(a, b) \ ({ \ - __typeof__(a) _a = (a); \ - __typeof__(b) _b = (b); \ + __typeof__(a) const &_a = (a); \ + __typeof__(b) const &_b = (b); \ _a < _b ? _a : _b; \ }) #define MIN3(a, b, c) MIN(MIN((a), (b)), (c)) diff --git a/common/lib/dsp/pid.cpp b/common/lib/dsp/pid.cpp index 205abb03e..b9462f4ff 100644 --- a/common/lib/dsp/pid.cpp +++ b/common/lib/dsp/pid.cpp @@ -20,18 +20,18 @@ PID::PID(double _dt, double _max, double _min, double _Kp, double _Kd, double PID::calculate(double setpoint, double pv) { // Calculate error - double error = setpoint - pv; + double const error = setpoint - pv; // Proportional term - double Pout = Kp * error; + double const Pout = Kp * error; // Integral term integral += error * dt; - double Iout = Ki * integral; + double const Iout = Ki * integral; // Derivative term - double derivative = (error - pre_error) / dt; - double Dout = Kd * derivative; + double const derivative = (error - pre_error) / dt; + double const Dout = Kd * derivative; // Calculate total output double output = Pout + Iout + Dout; diff --git a/common/lib/hist.cpp b/common/lib/hist.cpp index d2ad73df9..fde468f34 100644 --- a/common/lib/hist.cpp +++ b/common/lib/hist.cpp @@ -45,7 +45,7 @@ void Hist::put(double value) { // There is no warmup phase // TODO resolution = ? } else { - idx_t idx = std::round((value - low) / resolution); + idx_t const idx = std::round((value - low) / resolution); // Check bounds and increment if (idx >= (idx_t)data.size()) @@ -123,7 +123,7 @@ void Hist::print(Logger logger, bool details, std::string prefix) const { void Hist::plot(Logger logger) const { // Get highest bar - Hist::cnt_t max = *std::max_element(data.begin(), data.end()); + Hist::cnt_t const max = *std::max_element(data.begin(), data.end()); std::vector cols = { {-9, TableColumn::Alignment::RIGHT, "Value", "%+9.3g"}, @@ -136,9 +136,9 @@ void Hist::plot(Logger logger) const { table.header(); for (size_t i = 0; i < data.size(); i++) { - double value = low + (i)*resolution; - Hist::cnt_t cnt = data[i]; - int bar = cols[2].getWidth() * ((double)cnt / max); + double const value = low + (i)*resolution; + Hist::cnt_t const cnt = data[i]; + int const bar = cols[2].getWidth() * ((double)cnt / max); char *buf = strf("%s", ""); for (int i = 0; i < bar; i++) @@ -196,7 +196,7 @@ json_t *Hist::toJson() const { int Hist::dumpJson(FILE *f) const { json_t *j = Hist::toJson(); - int ret = json_dumpf(j, f, 0); + int const ret = json_dumpf(j, f, 0); json_decref(j); diff --git a/common/lib/kernel/devices/device_connection.cpp b/common/lib/kernel/devices/device_connection.cpp index e2cadfe87..f5c2b95b4 100644 --- a/common/lib/kernel/devices/device_connection.cpp +++ b/common/lib/kernel/devices/device_connection.cpp @@ -26,7 +26,7 @@ DeviceConnection DeviceConnection::from( auto logger = villas::Log::get("Builder: DeviceConnection"); // Bind the devicetree device to vfio driver - LinuxDriver driver( + LinuxDriver const driver( std::filesystem::path("/sys/bus/platform/drivers/vfio-platform")); driver.attach(device); @@ -55,9 +55,9 @@ void DeviceConnection::addToMemorygraph() const { // Create memorygraph edge from process to vfio device auto &mm = MemoryManager::get(); - size_t srcVertexId = mm.getProcessAddressSpace(); + size_t const srcVertexId = mm.getProcessAddressSpace(); const size_t mem_size = this->vfio_device->regionGetSize(0); - size_t targetVertexId = + size_t const targetVertexId = mm.getOrCreateAddressSpace(this->vfio_device->getName()); mm.createMapping(reinterpret_cast(mapping), 0, mem_size, "process to vfio", srcVertexId, targetVertexId); diff --git a/common/lib/kernel/devices/ip_device.cpp b/common/lib/kernel/devices/ip_device.cpp index acd10bf06..7c14277ff 100644 --- a/common/lib/kernel/devices/ip_device.cpp +++ b/common/lib/kernel/devices/ip_device.cpp @@ -25,13 +25,13 @@ IpDevice IpDevice::from(const std::filesystem::path unsafe_path) { } std::string IpDevice::ip_name() const { - int pos = name().find('.'); + int const pos = name().find('.'); return name().substr(pos + 1); } size_t IpDevice::addr() const { - size_t pos = name().find('.'); - std::string addr_hex = name().substr(0, pos); + size_t const pos = name().find('.'); + std::string const addr_hex = name().substr(0, pos); // Convert from hex-string to number std::stringstream ss; @@ -43,7 +43,7 @@ size_t IpDevice::addr() const { } bool IpDevice::is_path_valid(const std::filesystem::path unsafe_path) { - std::string assumed_device_name = unsafe_path.filename(); + std::string const assumed_device_name = unsafe_path.filename(); // Match format of hexaddr.devicename if (!std::regex_match(assumed_device_name, diff --git a/common/lib/kernel/devices/linux_driver.cpp b/common/lib/kernel/devices/linux_driver.cpp index f9e689868..024e8ef9c 100644 --- a/common/lib/kernel/devices/linux_driver.cpp +++ b/common/lib/kernel/devices/linux_driver.cpp @@ -26,7 +26,7 @@ void LinuxDriver::bind(const Device &device) const { } std::string LinuxDriver::name() const { - size_t pos = path.u8string().rfind('/'); + size_t const pos = path.u8string().rfind('/'); return path.u8string().substr(pos + 1); } diff --git a/common/lib/kernel/devices/pci_device.cpp b/common/lib/kernel/devices/pci_device.cpp index 377c7d697..f37993c93 100644 --- a/common/lib/kernel/devices/pci_device.cpp +++ b/common/lib/kernel/devices/pci_device.cpp @@ -8,6 +8,7 @@ */ #include +#include #include #include @@ -128,7 +129,7 @@ Id::Id(const std::string &str) : vendor(0), device(0), class_code(0) { *s++ = 0; if (tmp[0] && strcmp(tmp, "*")) { - long int x = strtol(tmp, &e, 16); + long int const x = strtol(tmp, &e, 16); if ((e && *e) || (x < 0 || x > 0xffff)) { free(tmp); @@ -143,7 +144,7 @@ Id::Id(const std::string &str) : vendor(0), device(0), class_code(0) { *c++ = 0; if (s[0] && strcmp(s, "*")) { - long int x = strtol(s, &e, 16); + long int const x = strtol(s, &e, 16); if ((e && *e) || (x < 0 || x > 0xffff)) { free(tmp); throw RuntimeError("Failed to parse PCI id: {}: Invalid device id", str); @@ -153,7 +154,7 @@ Id::Id(const std::string &str) : vendor(0), device(0), class_code(0) { } if (c && c[0] && strcmp(s, "*")) { - long int x = strtol(c, &e, 16); + long int const x = strtol(c, &e, 16); if ((e && *e) || (x < 0 || x > 0xffff)) { free(tmp); @@ -197,7 +198,7 @@ Slot::Slot(const std::string &str) : domain(0), bus(0), device(0), function(0) { buss = colon2; if (tmp[0] && strcmp(tmp, "*")) { - long int x = strtol(tmp, &e, 16); + long int const x = strtol(tmp, &e, 16); if ((e && *e) || (x < 0 || x > 0x7fffffff)) { free(tmp); throw RuntimeError("Failed to parse PCI slot: {}: invalid domain", @@ -210,7 +211,7 @@ Slot::Slot(const std::string &str) : domain(0), bus(0), device(0), function(0) { buss = tmp; if (buss[0] && strcmp(buss, "*")) { - long int x = strtol(buss, &e, 16); + long int const x = strtol(buss, &e, 16); if ((e && *e) || (x < 0 || x > 0xff)) { free(tmp); throw RuntimeError("Failed to parse PCI slot: {}: invalid bus", str); @@ -224,7 +225,7 @@ Slot::Slot(const std::string &str) : domain(0), bus(0), device(0), function(0) { *dot++ = 0; if (mid[0] && strcmp(mid, "*")) { - long int x = strtol(mid, &e, 16); + long int const x = strtol(mid, &e, 16); if ((e && *e) || (x < 0 || x > 0x1f)) { free(tmp); @@ -235,7 +236,7 @@ Slot::Slot(const std::string &str) : domain(0), bus(0), device(0), function(0) { } if (dot && dot[0] && strcmp(dot, "*")) { - long int x = strtol(dot, &e, 16); + long int const x = strtol(dot, &e, 16); if ((e && *e) || (x < 0 || x > 7)) { free(tmp); @@ -262,29 +263,34 @@ bool PciDevice::operator==(const PciDevice &f) { } std::list PciDevice::getRegions() const { - FILE *f; char sysfs[1024]; snprintf(sysfs, sizeof(sysfs), "%s/bus/pci/devices/%04x:%02x:%02x.%x/resource", SYSFS_PATH, slot.domain, slot.bus, slot.device, slot.function); - f = fopen(sysfs, "r"); + auto file_destructor = [](FILE *file) { fclose(file); }; + auto f = std::unique_ptr{fopen(sysfs, "r"), + file_destructor}; if (!f) throw SystemError("Failed to open resource mapping {}", sysfs); std::list regions; - ssize_t bytesRead; - char *line = nullptr; - size_t len = 0; - + // Cap to 8 regions, just because we don't know how many may exist. int reg_num = 0; + while (reg_num < 8) { + size_t len = 0; + char *line_ptr = nullptr; + auto line_destructor = [](char *line) { free(line); }; + auto ret = getline(&line_ptr, &len, f.get()); + auto line = std::unique_ptr{ + line_ptr, line_destructor}; + if (ret == -1) + break; - // Cap to 8 regions, just because we don't know how many may exist. - while (reg_num < 8 && (bytesRead = getline(&line, &len, f)) != -1) { unsigned long long tokens[3]; - char *s = line; + char *s = line.get(); for (int i = 0; i < 3; i++) { char *end; tokens[i] = strtoull(s, &end, 16); @@ -296,12 +302,6 @@ std::list PciDevice::getRegions() const { s = end; } - free(line); - - // Required for getline() to allocate a new buffer on the next iteration. - line = nullptr; - len = 0; - if (tokens[0] != tokens[1]) { // This is a valid region Region region; @@ -316,8 +316,6 @@ std::list PciDevice::getRegions() const { reg_num++; } - fclose(f); - return regions; } diff --git a/common/lib/kernel/devices/platform_device.cpp b/common/lib/kernel/devices/platform_device.cpp index e1f3610c6..5fedd51ae 100644 --- a/common/lib/kernel/devices/platform_device.cpp +++ b/common/lib/kernel/devices/platform_device.cpp @@ -15,24 +15,24 @@ using villas::kernel::devices::PlatformDevice; using villas::utils::write_to_file; std::optional> PlatformDevice::driver() const { - std::filesystem::path driver_symlink = + std::filesystem::path const driver_symlink = this->m_path / std::filesystem::path("driver"); if (!std::filesystem::is_symlink(driver_symlink)) return std::nullopt; - std::filesystem::path driver_path = + std::filesystem::path const driver_path = std::filesystem::canonical(driver_symlink); return std::make_optional(std::make_unique(driver_path)); } std::optional PlatformDevice::iommu_group() const { - std::filesystem::path symlink = + std::filesystem::path const symlink = std::filesystem::path(this->m_path.u8string() + "/iommu_group"); - std::filesystem::path link = std::filesystem::read_symlink(symlink); - std::string delimiter = "iommu_groups/"; - int pos = link.u8string().find(delimiter); + std::filesystem::path const link = std::filesystem::read_symlink(symlink); + std::string const delimiter = "iommu_groups/"; + int const pos = link.u8string().find(delimiter); int iommu_group = std::stoi(link.u8string().substr(pos + delimiter.length())); return std::make_optional(iommu_group); } diff --git a/common/lib/kernel/kernel.cpp b/common/lib/kernel/kernel.cpp index 8b9856323..91b4af494 100644 --- a/common/lib/kernel/kernel.cpp +++ b/common/lib/kernel/kernel.cpp @@ -9,6 +9,8 @@ #include #include #include +#include +#include #include #include @@ -31,7 +33,7 @@ Version villas::kernel::getVersion() { if (uname(&uts) < 0) throw SystemError("Failed to retrieve system identification"); - std::string rel = uts.release; + std::string const rel = uts.release; // Remove release part. E.g. 4.9.93-linuxkit-aufs auto sep = rel.find('-'); @@ -137,7 +139,7 @@ int villas::kernel::loadModule(const char *module) { return 0; } - pid_t pid = fork(); + pid_t const pid = fork(); switch (pid) { case -1: // Error return -1; @@ -180,12 +182,14 @@ int villas::kernel::getCmdlineParam(const char *param, char *buf, size_t len) { int ret; char cmdline[512], key[128], value[128], *lasts, *tok; - FILE *f = fopen(PROCFS_PATH "/cmdline", "r"); + auto file_destructor = [](FILE *file) { fclose(file); }; + auto f = std::unique_ptr{ + fopen(PROCFS_PATH "/cmdline", "r"), file_destructor}; if (!f) return -1; - if (!fgets(cmdline, sizeof(cmdline), f)) - goto out; + if (!fgets(cmdline, sizeof(cmdline), f.get())) + return -1; tok = strtok_r(cmdline, " \t", &lasts); do { @@ -206,9 +210,6 @@ int villas::kernel::getCmdlineParam(const char *param, char *buf, size_t len) { } } while ((tok = strtok_r(nullptr, " \t", &lasts))); -out: - fclose(f); - return -1; // Not found or error } @@ -249,22 +250,24 @@ int villas::kernel::setNrHugepages(int nr) { int villas::kernel::setIRQAffinity(unsigned irq, uintmax_t aff, uintmax_t *old) { char fn[64]; - FILE *f; int ret = 0; snprintf(fn, sizeof(fn), "/proc/irq/%u/smp_affinity", irq); - f = fopen(fn, "w+"); + auto file_destructor = [](FILE *file) { fclose(file); }; + auto f = std::unique_ptr{fopen(fn, "w+"), + file_destructor}; if (!f) return -1; // IRQ does not exist - if (old) - ret = fscanf(f, "%jx", old); + ret = fprintf(f.get(), "%jx", aff); + if (ret < 0) + return ret; - fprintf(f, "%jx", aff); - fclose(f); + if (old) + return fscanf(f.get(), "%jx", old); - return ret; + return 0; } int villas::kernel::get_cpu_frequency(uint64_t *freq) { diff --git a/common/lib/kernel/rt.cpp b/common/lib/kernel/rt.cpp index 2e7bab0c0..312a2cfac 100644 --- a/common/lib/kernel/rt.cpp +++ b/common/lib/kernel/rt.cpp @@ -25,7 +25,7 @@ namespace kernel { namespace rt { void init(int priority, int affinity) { - Logger logger = Log::get("kernel:rt"); + Logger const logger = Log::get("kernel:rt"); logger->info("Initialize sub-system"); @@ -84,7 +84,7 @@ void setProcessAffinity(int affinity) { assert(affinity != 0); - Logger logger = Log::get("kernel:rt"); + Logger const logger = Log::get("kernel:rt"); // Pin threads to CPUs by setting the affinity CpuSet cset_pin(affinity); @@ -103,7 +103,7 @@ void setThreadAffinity(pthread_t thread, int affinity) { assert(affinity != 0); - Logger logger = Log::get("kernel:rt"); + Logger const logger = Log::get("kernel:rt"); CpuSet cset_pin(affinity); @@ -121,7 +121,7 @@ void setPriority(int priority) { struct sched_param param; param.sched_priority = priority; - Logger logger = Log::get("kernel:rt"); + Logger const logger = Log::get("kernel:rt"); ret = sched_setscheduler(0, SCHED_FIFO, ¶m); if (ret) diff --git a/common/lib/kernel/vfio_container.cpp b/common/lib/kernel/vfio_container.cpp index cf30f29bd..1a9c85547 100644 --- a/common/lib/kernel/vfio_container.cpp +++ b/common/lib/kernel/vfio_container.cpp @@ -93,7 +93,7 @@ Container::Container(const std::vector &required_modules) // Check available VFIO extensions (IOMMU types) for (unsigned int i = VFIO_TYPE1_IOMMU; i < EXTENSION_SIZE; i++) { - int ret = ioctl(fd, VFIO_CHECK_EXTENSION, i); + int const ret = ioctl(fd, VFIO_CHECK_EXTENSION, i); extensions[i] = ret != 0; @@ -140,7 +140,8 @@ void Container::attachGroup(std::shared_ptr group) { group->getIndex(), fd); // Set IOMMU type - int iommu_type = isIommuEnabled() ? VFIO_TYPE1_IOMMU : VFIO_NOIOMMU_IOMMU; + int const iommu_type = + isIommuEnabled() ? VFIO_TYPE1_IOMMU : VFIO_NOIOMMU_IOMMU; ret = ioctl(fd, VFIO_SET_IOMMU, iommu_type); if (ret < 0) diff --git a/common/lib/kernel/vfio_device.cpp b/common/lib/kernel/vfio_device.cpp index b173faef7..437ed98de 100644 --- a/common/lib/kernel/vfio_device.cpp +++ b/common/lib/kernel/vfio_device.cpp @@ -16,9 +16,6 @@ #define _FILE_OFFSET_BITS 64 #endif -#include -#include -#include #include #include @@ -139,7 +136,7 @@ Device::~Device() { } reset(); - int ret = close(fd); + int const ret = close(fd); if (ret != 0) { log->error("Closing device fd {} failed", fd); } @@ -254,7 +251,7 @@ bool Device::pciEnable() { std::vector Device::initEventFds() { std::vector vectors; for (auto info_irq_vector : info_irq_vectors) { - Device::IrqVectorInfo irq = {0}; + Device::IrqVectorInfo irq = {{0}}; const size_t irqCount = info_irq_vector.count; const size_t irqSetSize = sizeof(struct vfio_irq_set) + sizeof(int) * irqCount; @@ -296,7 +293,7 @@ std::vector Device::initEventFds() { return vectors; } -int Device::pciMsiInit(int efds[]) { +int Device::pciMsiInit(int efds[32]) { // Check if this is really a vfio-pci device if (not isVfioPciDevice()) return -1; @@ -341,7 +338,7 @@ int Device::pciMsiInit(int efds[]) { return irqCount; } -int Device::pciMsiDeinit(int efds[]) { +int Device::pciMsiDeinit(int efds[32]) { Log::get("Device")->debug("Deinitializing MSI interrupts for device {}", name); // Check if this is really a vfio-pci device @@ -381,7 +378,7 @@ int Device::pciMsiDeinit(int efds[]) { return irqCount; } -bool Device::pciMsiFind(int nos[]) { +bool Device::pciMsiFind(int nos[32]) { int ret, idx, irq; char *end, *col, *last, line[1024], name[13]; FILE *f; @@ -467,7 +464,7 @@ bool Device::pciHotReset() { reset->count = 1; reset->group_fds[0] = groupFd; - int ret = ioctl(fd, VFIO_DEVICE_PCI_HOT_RESET, reset); + int const ret = ioctl(fd, VFIO_DEVICE_PCI_HOT_RESET, reset); const bool success = (ret == 0); delete[] reset_buf; diff --git a/common/lib/memory.cpp b/common/lib/memory.cpp index 8605b54aa..0f6593d1a 100644 --- a/common/lib/memory.cpp +++ b/common/lib/memory.cpp @@ -54,8 +54,8 @@ HostRam::HostRamAllocator::allocateBlock(size_t size) { } LinearAllocator::LinearAllocator( - const MemoryManager::AddressSpaceId &memoryAddrSpaceId, size_t memorySize, - size_t internalOffset) + const MemoryManager::AddressSpaceId &memoryAddrSpaceId, + [[maybe_unused]] size_t memorySize, [[maybe_unused]] size_t internalOffset) : BaseAllocator(memoryAddrSpaceId), nextFreeAddress(0), memorySize(memorySize), internalOffset(internalOffset), allocationCount(0) { @@ -63,6 +63,7 @@ LinearAllocator::LinearAllocator( if (const size_t paddingBytes = getAlignmentPadding(internalOffset)) { assert(paddingBytes < memorySize); + // TODO: This modifies the parameters, not the members. Is this a bug? internalOffset += paddingBytes; memorySize -= paddingBytes; } diff --git a/common/lib/memory_manager.cpp b/common/lib/memory_manager.cpp index 1c5f7cc53..06fd1faf6 100644 --- a/common/lib/memory_manager.cpp +++ b/common/lib/memory_manager.cpp @@ -37,7 +37,7 @@ MemoryManager::getOrCreateAddressSpace(const std::string &name) { return addrSpaceLookup.at(name); } catch (const std::out_of_range &) { // Does not yet exist, create - std::shared_ptr addrSpace(new AddressSpace); + std::shared_ptr const addrSpace(new AddressSpace); addrSpace->name = name; // Cache it for the next access @@ -52,7 +52,7 @@ MemoryManager::createMapping(uintptr_t src, uintptr_t dest, size_t size, const std::string &name, MemoryManager::AddressSpaceId fromAddrSpace, MemoryManager::AddressSpaceId toAddrSpace) { - std::shared_ptr mapping(new Mapping); + std::shared_ptr const mapping(new Mapping); mapping->name = name; mapping->src = src; @@ -164,7 +164,7 @@ MemoryTranslation::getForeignAddr(uintptr_t addrInLocalAddrSpace) const { MemoryTranslation & MemoryTranslation::operator+=(const MemoryTranslation &other) { - Logger logger = Log::get("MemoryTranslation"); + Logger const logger = Log::get("MemoryTranslation"); // Set level to debug to enable debug output logger->set_level(spdlog::level::info); diff --git a/common/lib/popen.cpp b/common/lib/popen.cpp index 99fc2a60c..2b3ba781e 100644 --- a/common/lib/popen.cpp +++ b/common/lib/popen.cpp @@ -168,7 +168,7 @@ void PopenStream::open() { } int PopenStream::close() { - int ret = Popen::close(); + int const ret = Popen::close(); input.stream.reset(); output.stream.reset(); diff --git a/common/lib/table.cpp b/common/lib/table.cpp index 8c1b50002..d5fe182c6 100644 --- a/common/lib/table.cpp +++ b/common/lib/table.cpp @@ -120,9 +120,9 @@ void Table::row(int count, ...) { for (unsigned i = 0; i < columns.size(); ++i) { char *col = vstrf(columns[i].format.c_str(), args); - int l = strlenp(col); - int r = strlen(col); - int w = columns[i]._width + r - l; + int const l = strlenp(col); + int const r = strlen(col); + int const w = columns[i]._width + r - l; if (columns[i].align == TableColumn::Alignment::LEFT) strcatf(&line, " %-*.*s " ANSI_RESET, w, w, col); diff --git a/common/lib/task.cpp b/common/lib/task.cpp index 5d6478e21..df0e388b4 100644 --- a/common/lib/task.cpp +++ b/common/lib/task.cpp @@ -38,8 +38,8 @@ void Task::setTimeout(double to) { clock_gettime(clock, &now); - struct timespec timeout = time_from_double(to); - struct timespec next = time_add(&now, &timeout); + struct timespec const timeout = time_from_double(to); + struct timespec const next = time_add(&now, &timeout); setNext(&next); } @@ -51,8 +51,8 @@ void Task::setNext(const struct timespec *nxt) { #if PERIODIC_TASK_IMPL == TIMERFD int ret; - struct itimerspec its = {.it_interval = (struct timespec){0, 0}, - .it_value = next}; + struct itimerspec const its = {.it_interval = (struct timespec){0, 0}, + .it_value = next}; ret = timerfd_settime(fd, TFD_TIMER_ABSTIME, &its, nullptr); if (ret) @@ -79,7 +79,7 @@ void Task::setRate(double rate) { return setNext(&next); #elif PERIODIC_TASK_IMPL == TIMERFD int ret; - struct itimerspec its = {.it_interval = period, .it_value = period}; + struct itimerspec const its = {.it_interval = period, .it_value = period}; ret = timerfd_settime(fd, 0, &its, nullptr); if (ret) @@ -154,8 +154,8 @@ uint64_t Task::wait() { void Task::stop() { #if PERIODIC_TASK_IMPL == TIMERFD int ret; - struct itimerspec its = {.it_interval = (struct timespec){0, 0}, - .it_value = (struct timespec){0, 0}}; + struct itimerspec const its = {.it_interval = (struct timespec){0, 0}, + .it_value = (struct timespec){0, 0}}; ret = timerfd_settime(fd, 0, &its, nullptr); if (ret) diff --git a/common/lib/terminal.cpp b/common/lib/terminal.cpp index cb6540262..7b73159e6 100644 --- a/common/lib/terminal.cpp +++ b/common/lib/terminal.cpp @@ -23,7 +23,7 @@ Terminal::Terminal() { isTty = isatty(STDERR_FILENO); - Logger logger = Log::get("terminal"); + Logger const logger = Log::get("terminal"); if (isTty) { struct sigaction sa_resize; @@ -57,7 +57,7 @@ void Terminal::resize(int, siginfo_t *, void *) { if (!current) current = new Terminal(); - Logger logger = Log::get("terminal"); + Logger const logger = Log::get("terminal"); int ret; diff --git a/common/lib/timing.cpp b/common/lib/timing.cpp index acbc7e1ea..0bb2d8543 100644 --- a/common/lib/timing.cpp +++ b/common/lib/timing.cpp @@ -57,14 +57,14 @@ double time_to_double(const struct timespec *ts) { } double time_delta(const struct timespec *start, const struct timespec *end) { - struct timespec diff = time_diff(start, end); + struct timespec const diff = time_diff(start, end); return time_to_double(&diff); } ssize_t time_cmp(const struct timespec *a, const struct timespec *b) { - ssize_t sd = a->tv_sec - b->tv_sec; - ssize_t nsd = a->tv_nsec - b->tv_nsec; + ssize_t const sd = a->tv_sec - b->tv_sec; + ssize_t const nsd = a->tv_nsec - b->tv_nsec; return sd != 0 ? sd : nsd; } diff --git a/common/lib/tsc.cpp b/common/lib/tsc.cpp index 44f95d726..c6daa45cf 100644 --- a/common/lib/tsc.cpp +++ b/common/lib/tsc.cpp @@ -35,7 +35,7 @@ int tsc_init(struct Tsc *t) { t->frequency = ecx * ebx / eax; else { #ifdef __linux__ - int ret = kernel::get_cpu_frequency(&t->frequency); + int const ret = kernel::get_cpu_frequency(&t->frequency); if (ret) return ret; #endif diff --git a/common/lib/utils.cpp b/common/lib/utils.cpp index 61666029a..18f910b83 100644 --- a/common/lib/utils.cpp +++ b/common/lib/utils.cpp @@ -90,7 +90,7 @@ int signalsInit(void (*cb)(int signal, siginfo_t *sinfo, void *ctx), std::list cbSignals, const std::list &ignoreSignals) { int ret; - Logger logger = Log::get("signals"); + Logger const logger = Log::get("signals"); logger->info("Initialize subsystem"); @@ -196,8 +196,8 @@ double randf() { return (double)random() / RAND_MAX; } char *vstrcatf(char **dest, const char *fmt, va_list ap) { char *tmp; - int n = *dest ? strlen(*dest) : 0; - int i = vasprintf(&tmp, fmt, ap); + int const n = *dest ? strlen(*dest) : 0; + int const i = vasprintf(&tmp, fmt, ap); *dest = (char *)(realloc(*dest, n + i + 1)); if (*dest != nullptr) diff --git a/common/lib/uuid.cpp b/common/lib/uuid.cpp index 6c7e5c17b..53c2ad0a5 100644 --- a/common/lib/uuid.cpp +++ b/common/lib/uuid.cpp @@ -76,7 +76,7 @@ int villas::uuid::generateFromString(uuid_t out, const std::string &data, int villas::uuid::generateFromJson(uuid_t out, json_t *json, const uuid_t ns) { char *str = json_dumps(json, JSON_COMPACT | JSON_SORT_KEYS); - int ret = generateFromString(out, str, ns); + int const ret = generateFromString(out, str, ns); free(str); diff --git a/common/tests/unit/buffer.cpp b/common/tests/unit/buffer.cpp index f6043c0d8..dd04551a4 100644 --- a/common/tests/unit/buffer.cpp +++ b/common/tests/unit/buffer.cpp @@ -24,13 +24,9 @@ Test(buffer, decode) { json_t *k; const char *e = "{\"id\": \"5a786626-fbc6-4c04-98c2-48027e68c2fa\"}"; - size_t len = strlen(e); + size_t const len = strlen(e); -#pragma GCC diagnostic push -// Workaround for compiler bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106199 -#pragma GCC diagnostic ignored "-Wstringop-overflow" buf.insert(buf.begin(), e, e + len); -#pragma GCC diagnostic pop k = json_loads(e, 0, nullptr); cr_assert_not_null(k); diff --git a/common/tests/unit/graph.cpp b/common/tests/unit/graph.cpp index 55d9c7551..3349dddfb 100644 --- a/common/tests/unit/graph.cpp +++ b/common/tests/unit/graph.cpp @@ -19,14 +19,14 @@ using namespace villas; TestSuite(graph, .description = "Graph library"); Test(graph, basic, .description = "DirectedGraph") { - Logger logger = Log::get("test:graph:basic"); + Logger const logger = Log::get("test:graph:basic"); villas::graph::DirectedGraph<> g("test:graph:basic"); logger->info("Testing basic graph construction and modification"); - std::shared_ptr v1(new villas::graph::Vertex); - std::shared_ptr v2(new villas::graph::Vertex); - std::shared_ptr v3(new villas::graph::Vertex); + std::shared_ptr const v1(new villas::graph::Vertex); + std::shared_ptr const v2(new villas::graph::Vertex); + std::shared_ptr const v3(new villas::graph::Vertex); auto v1id = g.addVertex(v1); auto v2id = g.addVertex(v2); @@ -49,18 +49,18 @@ Test(graph, basic, .description = "DirectedGraph") { } Test(graph, path, .description = "Find path") { - Logger logger = Log::get("test:graph:path"); + Logger const logger = Log::get("test:graph:path"); logger->info("Testing path finding algorithm"); using Graph = villas::graph::DirectedGraph<>; Graph g("test:graph:path"); - std::shared_ptr v1(new villas::graph::Vertex); - std::shared_ptr v2(new villas::graph::Vertex); - std::shared_ptr v3(new villas::graph::Vertex); - std::shared_ptr v4(new villas::graph::Vertex); - std::shared_ptr v5(new villas::graph::Vertex); - std::shared_ptr v6(new villas::graph::Vertex); + std::shared_ptr const v1(new villas::graph::Vertex); + std::shared_ptr const v2(new villas::graph::Vertex); + std::shared_ptr const v3(new villas::graph::Vertex); + std::shared_ptr const v4(new villas::graph::Vertex); + std::shared_ptr const v5(new villas::graph::Vertex); + std::shared_ptr const v6(new villas::graph::Vertex); auto v1id = g.addVertex(v1); auto v2id = g.addVertex(v2); @@ -110,7 +110,7 @@ Test(graph, path, .description = "Find path") { } Test(graph, memory_manager, .description = "Global Memory Manager") { - Logger logger = Log::get("test:graph:mm"); + Logger const logger = Log::get("test:graph:mm"); auto &mm = villas::MemoryManager::get(); logger->info("Create address spaces"); diff --git a/common/tests/unit/kernel.cpp b/common/tests/unit/kernel.cpp index dd38c607d..388148429 100644 --- a/common/tests/unit/kernel.cpp +++ b/common/tests/unit/kernel.cpp @@ -66,8 +66,8 @@ Test(kernel, version) { using villas::utils::Version; Version ver = villas::kernel::getVersion(); - Version ver1 = {100, 5}; - Version ver2 = {2, 6}; + Version const ver1 = {100, 5}; + Version const ver2 = {2, 6}; cr_assert_lt(ver, ver1); cr_assert_gt(ver, ver2); diff --git a/common/tests/unit/list.cpp b/common/tests/unit/list.cpp index ae39da14e..b7f8787aa 100644 --- a/common/tests/unit/list.cpp +++ b/common/tests/unit/list.cpp @@ -122,7 +122,7 @@ Test(list, basics) { }); for (size_t j = 0, i = 99; j <= 99; j++, i--) { - uintptr_t k = (uintptr_t)list_at(&l, j); + uintptr_t const k = (uintptr_t)list_at(&l, j); cr_assert_eq(k, i, "Is %zu, expected %zu", k, i); } diff --git a/common/tests/unit/task.cpp b/common/tests/unit/task.cpp index 6c0241ed6..36f37474a 100644 --- a/common/tests/unit/task.cpp +++ b/common/tests/unit/task.cpp @@ -17,8 +17,9 @@ using namespace villas; TestSuite(task, .description = "Periodic timer tasks"); Test(task, rate, .timeout = 10) { - int runs = 10; - double rate = 5, waited; + int const runs = 10; + double const rate = 5; + double waited; struct timespec start, end; Task task(CLOCK_MONOTONIC); @@ -50,7 +51,7 @@ Test(task, wait_until, .timeout = 5) { Task task(CLOCK_REALTIME); - double waitfor = 3.423456789; + double const waitfor = 3.423456789; start = time_now(); diff = time_from_double(waitfor); @@ -64,7 +65,7 @@ Test(task, wait_until, .timeout = 5) { cr_assert_eq(ret, 1); - double waited = time_delta(&start, &end); + double const waited = time_delta(&start, &end); cr_assert_float_eq(waited, waitfor, 1e-2, "We slept for %f instead of %f secs", waited, waitfor); diff --git a/common/tests/unit/timing.cpp b/common/tests/unit/timing.cpp index a7409c3f1..20d69e2b7 100644 --- a/common/tests/unit/timing.cpp +++ b/common/tests/unit/timing.cpp @@ -15,18 +15,19 @@ TestSuite(timing, .description = "Time measurements"); Test(timing, time_now) { - struct timespec now1 = time_now(); - struct timespec now2 = time_now(); + struct timespec const now1 = time_now(); + struct timespec const now2 = time_now(); cr_assert(time_cmp(&now1, &now2) <= 0, "time_now() was reordered!"); } Test(timing, time_diff) { - struct timespec ts1 = {.tv_sec = 0, .tv_nsec = 1}; // Value doesnt matter - struct timespec ts2 = {.tv_sec = 1, - .tv_nsec = 0}; // Overflow in nano seconds! + struct timespec const ts1 = {.tv_sec = 0, + .tv_nsec = 1}; // Value doesnt matter + struct timespec const ts2 = {.tv_sec = 1, + .tv_nsec = 0}; // Overflow in nano seconds! - struct timespec ts3 = time_diff(&ts1, &ts2); + struct timespec const ts3 = time_diff(&ts1, &ts2); // ts4 == ts2? cr_assert_eq(ts3.tv_sec, 0); @@ -34,12 +35,12 @@ Test(timing, time_diff) { } Test(timing, time_add) { - struct timespec ts1 = {.tv_sec = 1, - .tv_nsec = 999999999}; // Value doesnt matter - struct timespec ts2 = {.tv_sec = 1, - .tv_nsec = 1}; // Overflow in nano seconds! + struct timespec const ts1 = {.tv_sec = 1, + .tv_nsec = 999999999}; // Value doesnt matter + struct timespec const ts2 = {.tv_sec = 1, + .tv_nsec = 1}; // Overflow in nano seconds! - struct timespec ts3 = time_add(&ts1, &ts2); + struct timespec const ts3 = time_add(&ts1, &ts2); // ts4 == ts2? cr_assert_eq(ts3.tv_sec, 3); @@ -47,29 +48,30 @@ Test(timing, time_add) { } Test(timing, time_delta) { - struct timespec ts1 = {.tv_sec = 1, .tv_nsec = 123}; // Value doesnt matter - struct timespec ts2 = {.tv_sec = 5, - .tv_nsec = 246}; // Overflow in nano seconds! + struct timespec const ts1 = {.tv_sec = 1, + .tv_nsec = 123}; // Value doesnt matter + struct timespec const ts2 = {.tv_sec = 5, + .tv_nsec = 246}; // Overflow in nano seconds! - double delta = time_delta(&ts1, &ts2); + double const delta = time_delta(&ts1, &ts2); cr_assert_float_eq(delta, 4 + 123e-9, 1e-9); } Test(timing, time_from_double) { - double ref = 1234.56789; + double const ref = 1234.56789; - struct timespec ts = time_from_double(ref); + struct timespec const ts = time_from_double(ref); cr_assert_eq(ts.tv_sec, 1234); cr_assert_eq(ts.tv_nsec, 567890000); } Test(timing, time_to_from_double) { - double ref = 1234.56789; + double const ref = 1234.56789; - struct timespec ts = time_from_double(ref); - double dbl = time_to_double(&ts); + struct timespec const ts = time_from_double(ref); + double const dbl = time_to_double(&ts); cr_assert_float_eq(dbl, ref, 1e-9); } diff --git a/common/tests/unit/tsc.cpp b/common/tests/unit/tsc.cpp index 6e73dc04a..411a52c41 100644 --- a/common/tests/unit/tsc.cpp +++ b/common/tests/unit/tsc.cpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include #define CNT (1 << 18) @@ -38,7 +38,8 @@ Test(tsc, increasing) { Test(tsc, sleep) { int ret; - double delta, duration = 1; + double delta; + double const duration = 1; struct timespec start, stop; struct Tsc tsc; uint64_t start_cycles, end_cycles; @@ -57,6 +58,7 @@ Test(tsc, sleep) { clock_gettime(CLOCK_MONOTONIC, &stop); delta = time_delta(&start, &stop); - cr_assert_float_eq(delta, duration, 1e-4, "Error: %f, Delta: %lf, Freq: %llu", - delta - duration, delta, tsc.frequency); + cr_assert_float_eq(delta, duration, 1e-4, + "Error: %f, Delta: %lf, Freq: %" PRIu64, delta - duration, + delta, tsc.frequency); } diff --git a/common/tests/unit/utils.cpp b/common/tests/unit/utils.cpp index ee31f7f7d..e87057ac1 100644 --- a/common/tests/unit/utils.cpp +++ b/common/tests/unit/utils.cpp @@ -5,6 +5,8 @@ * SPDX-License-Identifier: Apache-2.0 */ +#include + #include #include @@ -22,7 +24,7 @@ TestSuite(utils, .description = "Utilities"); Test(utils, box_muller) { double n; unsigned sigma[3] = {0}; - unsigned iter = 1000000; + unsigned const iter = 1000000; for (unsigned i = 0; i < iter; i++) { n = boxMuller(0, 1); @@ -54,17 +56,17 @@ Test(utils, box_muller) { Test(utils, cpuset) { using villas::utils::CpuSet; - uintmax_t int1 = 0x1234567890ABCDEFULL; + uintmax_t const int1 = 0x1234567890ABCDEFULL; CpuSet cset1(int1); - std::string cset1_str = cset1; + std::string const cset1_str = cset1; CpuSet cset2(cset1_str); cr_assert_eq(cset1, cset2); - uintmax_t int2 = cset2; + uintmax_t const int2 = cset2; cr_assert_eq(int1, int2); @@ -86,9 +88,10 @@ Test(utils, cpuset) { cset4.clear(6); cr_assert_not(cset4[6]); - cr_assert_str_eq(static_cast(cset4).c_str(), "1-5"); + auto cset4_str = static_cast(cset4); + cr_assert_str_eq(cset4_str.c_str(), "1-5"); - cr_assert_any_throw(CpuSet cset5("0-")); + cr_assert_any_throw(CpuSet const cset5("0-")); CpuSet cset6; cr_assert(cset6.empty()); @@ -167,9 +170,9 @@ Test(utils, version) { Version v2 = Version("1.3"); Version v3 = Version("55"); Version v4 = Version("66"); - Version v5 = Version(66); + Version const v5 = Version(66); Version v6 = Version(1, 2, 5); - Version v7 = Version("1.2.5"); + Version const v7 = Version("1.2.5"); cr_assert_lt(v1, v2); cr_assert_eq(v1, v1); @@ -181,7 +184,10 @@ Test(utils, version) { Test(utils, sha1sum) { int ret; - FILE *f = tmpfile(); + auto file_destructor = [](FILE *file) { fclose(file); }; + auto f = std::unique_ptr{tmpfile(), + file_destructor}; + cr_assert(f); unsigned char hash[SHA_DIGEST_LENGTH]; unsigned char expected[SHA_DIGEST_LENGTH] = { @@ -192,15 +198,13 @@ Test(utils, sha1sum) { for (int i = 0, a = 0, b = 1, c; i < 512; i++, a = b, b = c) { c = a + b; - fwrite((void *)&c, sizeof(c), 1, f); + fwrite((void *)&c, sizeof(c), 1, f.get()); } - ret = sha1sum(f, hash); + ret = sha1sum(f.get(), hash); cr_assert_eq(ret, 0); cr_assert_arr_eq(hash, expected, SHA_DIGEST_LENGTH); - - fclose(f); } Test(utils, decolor) { diff --git a/fpga/include/villas/fpga/card_parser.hpp b/fpga/include/villas/fpga/card_parser.hpp index 20e8925ea..41078d25b 100644 --- a/fpga/include/villas/fpga/card_parser.hpp +++ b/fpga/include/villas/fpga/card_parser.hpp @@ -34,7 +34,7 @@ class CardParser { json_error_t err; json_t *ignored_ips_array = nullptr; - int ret = json_unpack_ex( + int const ret = json_unpack_ex( json_card, &err, 0, "{ s: o, s?: i, s?: b, s?: s, s?: s, s?: b, s?: o, s?: o}", "ips", &json_ips, "affinity", &affinity, "do_reset", &do_reset, "slot", diff --git a/fpga/include/villas/fpga/core.hpp b/fpga/include/villas/fpga/core.hpp index 0210d5fed..334287994 100644 --- a/fpga/include/villas/fpga/core.hpp +++ b/fpga/include/villas/fpga/core.hpp @@ -225,7 +225,7 @@ class CoreFactory : public plugin::Plugin { // Returns a running and checked FPGA IP static std::list> make(Card *card, json_t *json_ips); - virtual std::string getType() const { return "core"; } + std::string getType() const override { return "core"; } protected: enum PollingMode { @@ -233,7 +233,7 @@ class CoreFactory : public plugin::Plugin { IRQ, }; - Logger getLogger() { return villas::Log::get(getName()); } + Logger getLogger() override { return villas::Log::get(getName()); } // Configure IP instance from JSON config virtual void parse(Core &, json_t *) {} @@ -255,15 +255,15 @@ template class CorePlugin : public CoreFactory { public: - virtual std::string getName() const { return name; } + std::string getName() const override { return name; } - virtual std::string getDescription() const { return desc; } + std::string getDescription() const override { return desc; } private: - virtual Vlnv getCompatibleVlnv() const { return Vlnv(vlnv); } + Vlnv getCompatibleVlnv() const override { return Vlnv(vlnv); } // Create a concrete IP instance - Core *make() const { return new T; }; + Core *make() const override { return new T; }; }; } // namespace ip diff --git a/fpga/include/villas/fpga/ips/aurora.hpp b/fpga/include/villas/fpga/ips/aurora.hpp index 7c969687d..904a41fc6 100644 --- a/fpga/include/villas/fpga/ips/aurora.hpp +++ b/fpga/include/villas/fpga/ips/aurora.hpp @@ -18,15 +18,17 @@ class Aurora : public Node { static constexpr const char *masterPort = "m_axis"; static constexpr const char *slavePort = "s_axis"; - virtual void dump() override; + void dump() override; - std::list getMemoryBlocks() const { return {registerMemory}; } + std::list getMemoryBlocks() const override { + return {registerMemory}; + } - const StreamVertex &getDefaultSlavePort() const { + const StreamVertex &getDefaultSlavePort() const override { return getSlavePort(slavePort); } - const StreamVertex &getDefaultMasterPort() const { + const StreamVertex &getDefaultMasterPort() const override { return getMasterPort(masterPort); } diff --git a/fpga/include/villas/fpga/ips/aurora_xilinx.hpp b/fpga/include/villas/fpga/ips/aurora_xilinx.hpp index 4da5628f0..29d6c6bac 100644 --- a/fpga/include/villas/fpga/ips/aurora_xilinx.hpp +++ b/fpga/include/villas/fpga/ips/aurora_xilinx.hpp @@ -18,11 +18,11 @@ class AuroraXilinx : public Node { static constexpr const char *masterPort = "USER_DATA_M_AXI_RX"; static constexpr const char *slavePort = "USER_DATA_S_AXI_TX"; - const StreamVertex &getDefaultSlavePort() const { + const StreamVertex &getDefaultSlavePort() const override { return getSlavePort(slavePort); } - const StreamVertex &getDefaultMasterPort() const { + const StreamVertex &getDefaultMasterPort() const override { return getMasterPort(masterPort); } }; diff --git a/fpga/include/villas/fpga/ips/axis_cache.hpp b/fpga/include/villas/fpga/ips/axis_cache.hpp index 53153164d..d19d4b7d7 100644 --- a/fpga/include/villas/fpga/ips/axis_cache.hpp +++ b/fpga/include/villas/fpga/ips/axis_cache.hpp @@ -18,9 +18,9 @@ namespace ip { class AxisCache : public Node { public: AxisCache(); - virtual ~AxisCache(); - virtual bool init() override; - virtual bool check() override; + ~AxisCache() override; + bool init() override; + bool check() override; void invalidate(); protected: diff --git a/fpga/include/villas/fpga/ips/bram.hpp b/fpga/include/villas/fpga/ips/bram.hpp index 5381f5afb..b36f336a1 100644 --- a/fpga/include/villas/fpga/ips/bram.hpp +++ b/fpga/include/villas/fpga/ips/bram.hpp @@ -20,14 +20,16 @@ class Bram : public Core { friend class BramFactory; public: - virtual bool init() override; + bool init() override; LinearAllocator &getAllocator() { return *allocator; } private: static constexpr const char *memoryBlock = "Mem0"; - std::list getMemoryBlocks() const { return {memoryBlock}; } + std::list getMemoryBlocks() const override { + return {memoryBlock}; + } size_t size; std::unique_ptr allocator; @@ -36,20 +38,20 @@ class Bram : public Core { class BramFactory : public CoreFactory { public: - virtual std::string getName() const { return "bram"; } + std::string getName() const override { return "bram"; } - virtual std::string getDescription() const { return "Block RAM"; } + std::string getDescription() const override { return "Block RAM"; } private: - virtual Vlnv getCompatibleVlnv() const { + Vlnv getCompatibleVlnv() const override { return Vlnv("xilinx.com:ip:axi_bram_ctrl:"); } // Create a concrete IP instance - Core *make() const { return new Bram; }; + Core *make() const override { return new Bram; }; protected: - virtual void parse(Core &, json_t *) override; + void parse(Core &, json_t *) override; }; } // namespace ip diff --git a/fpga/include/villas/fpga/ips/dino.hpp b/fpga/include/villas/fpga/ips/dino.hpp index e97800a71..9c964c7dd 100644 --- a/fpga/include/villas/fpga/ips/dino.hpp +++ b/fpga/include/villas/fpga/ips/dino.hpp @@ -53,8 +53,8 @@ class Dino : public Node { enum Gain { GAIN_1 = 0, GAIN_2 = 1, GAIN_5 = 2, GAIN_10 = 3 }; Dino(); - virtual ~Dino(); - virtual bool init() override; + ~Dino() override; + bool init() override; void setI2c(std::shared_ptr i2cdev, uint8_t i2c_channel) { this->i2cdev = i2cdev; this->i2c_channel = i2c_channel; @@ -89,8 +89,8 @@ class Dino : public Node { class DinoAdc : public Dino { public: DinoAdc(); - virtual ~DinoAdc(); - virtual void configureHardware() override; + ~DinoAdc() override; + void configureHardware() override; /* Set the configuration of the ADC registers * @@ -109,42 +109,40 @@ class DinoAdc : public Dino { class DinoDac : public Dino { public: DinoDac(); - virtual ~DinoDac(); - virtual void configureHardware() override; + ~DinoDac() override; + void configureHardware() override; void setGain(Gain gain); Gain getGain(); }; class DinoFactory : NodeFactory { public: - virtual std::string getDescription() const override { - return "Dino Analog I/O"; - } + std::string getDescription() const override { return "Dino Analog I/O"; } protected: - virtual void parse(Core &ip, json_t *json) override; + void parse(Core &ip, json_t *json) override; }; class DinoAdcFactory : DinoFactory { public: - virtual std::string getName() const { return "dinoAdc"; } + std::string getName() const override { return "dinoAdc"; } private: - virtual Vlnv getCompatibleVlnv() const { + Vlnv getCompatibleVlnv() const override { return Vlnv("xilinx.com:module_ref:dinoif_adc:"); } - Core *make() const { return new DinoAdc; }; + Core *make() const override { return new DinoAdc; }; }; class DinoDacFactory : DinoFactory { public: - virtual std::string getName() const { return "dinoDac"; } + std::string getName() const override { return "dinoDac"; } private: - virtual Vlnv getCompatibleVlnv() const { + Vlnv getCompatibleVlnv() const override { return Vlnv("xilinx.com:module_ref:dinoif_dac:"); } - Core *make() const { return new DinoDac; }; + Core *make() const override { return new DinoDac; }; }; } // namespace ip diff --git a/fpga/include/villas/fpga/ips/dma.hpp b/fpga/include/villas/fpga/ips/dma.hpp index 44e26c25c..abf9a092d 100644 --- a/fpga/include/villas/fpga/ips/dma.hpp +++ b/fpga/include/villas/fpga/ips/dma.hpp @@ -25,9 +25,9 @@ class Dma : public Node { public: friend class DmaFactory; - virtual ~Dma(); + ~Dma() override; - virtual bool init() override; + bool init() override; bool reset() override; @@ -84,7 +84,7 @@ class Dma : public Node { bool isMemoryBlockAccesible(const MemoryBlock &mem, const std::string &interface); - virtual void dump() override; + void dump() override; private: bool writeScatterGather(const void *buf, size_t len); @@ -154,14 +154,14 @@ class Dma : public Node { class DmaFactory : NodeFactory { public: - virtual std::string getName() const override { return "dma"; } + std::string getName() const override { return "dma"; } - virtual std::string getDescription() const override { + std::string getDescription() const override { return "Xilinx's AXI4 Direct Memory Access Controller"; } private: - virtual Vlnv getCompatibleVlnv() const override { + Vlnv getCompatibleVlnv() const override { return Vlnv("xilinx.com:ip:axi_dma:"); } @@ -169,9 +169,9 @@ class DmaFactory : NodeFactory { Core *make() const override { return new Dma; }; protected: - virtual void parse(Core &ip, json_t *json) override; + void parse(Core &ip, json_t *json) override; - virtual void configurePollingMode(Core &ip, PollingMode mode) override { + void configurePollingMode(Core &ip, PollingMode mode) override { dynamic_cast(ip).polling = (mode == POLL); } }; diff --git a/fpga/include/villas/fpga/ips/emc.hpp b/fpga/include/villas/fpga/ips/emc.hpp index 0c93f4094..5907dc746 100644 --- a/fpga/include/villas/fpga/ips/emc.hpp +++ b/fpga/include/villas/fpga/ips/emc.hpp @@ -17,7 +17,7 @@ namespace ip { class EMC : public Core { public: - virtual bool init() override; + bool init() override; bool flash(uint32_t offset, const std::string &filename); bool flash(uint32_t offset, uint32_t length, uint8_t *data); @@ -29,7 +29,7 @@ class EMC : public Core { static constexpr char registerMemory[] = "Reg"; - std::list getMemoryBlocks() const { + std::list getMemoryBlocks() const override { return {registerMemory}; } }; diff --git a/fpga/include/villas/fpga/ips/fifo.hpp b/fpga/include/villas/fpga/ips/fifo.hpp index e28c0ef02..3dff5081d 100644 --- a/fpga/include/villas/fpga/ips/fifo.hpp +++ b/fpga/include/villas/fpga/ips/fifo.hpp @@ -22,9 +22,9 @@ class Fifo : public Node { public: friend class FifoFactory; - virtual bool init() override; + bool init() override; - virtual bool stop() override; + bool stop() override; size_t write(const void *buf, size_t len); size_t read(void *buf, size_t len); @@ -34,7 +34,7 @@ class Fifo : public Node { static constexpr char axi4Memory[] = "Mem1"; static constexpr char irqName[] = "interrupt"; - std::list getMemoryBlocks() const { + std::list getMemoryBlocks() const override { return {registerMemory, axi4Memory}; } diff --git a/fpga/include/villas/fpga/ips/gpio.hpp b/fpga/include/villas/fpga/ips/gpio.hpp index c4b85b5ea..11ef20684 100644 --- a/fpga/include/villas/fpga/ips/gpio.hpp +++ b/fpga/include/villas/fpga/ips/gpio.hpp @@ -16,12 +16,12 @@ namespace ip { class Gpio : public Core { public: - virtual bool init() override; + bool init() override; private: static constexpr char registerMemory[] = "Reg"; - std::list getMemoryBlocks() const { + std::list getMemoryBlocks() const override { return {registerMemory}; } }; diff --git a/fpga/include/villas/fpga/ips/gpu2rtds.hpp b/fpga/include/villas/fpga/ips/gpu2rtds.hpp index 0177aeebb..754929df2 100644 --- a/fpga/include/villas/fpga/ips/gpu2rtds.hpp +++ b/fpga/include/villas/fpga/ips/gpu2rtds.hpp @@ -21,7 +21,7 @@ class Gpu2Rtds : public Node, public Hls { public: friend class Gpu2RtdsFactory; - virtual bool init() override; + bool init() override; void dump(spdlog::level::level_enum logLevel = spdlog::level::info); @@ -31,7 +31,7 @@ class Gpu2Rtds : public Node, public Hls { size_t getMaxFrameSize(); - const StreamVertex &getDefaultMasterPort() const { + const StreamVertex &getDefaultMasterPort() const override { return getMasterPort(rtdsOutputStreamPort); } diff --git a/fpga/include/villas/fpga/ips/hls.hpp b/fpga/include/villas/fpga/ips/hls.hpp index e62874b38..979d01b28 100644 --- a/fpga/include/villas/fpga/ips/hls.hpp +++ b/fpga/include/villas/fpga/ips/hls.hpp @@ -16,7 +16,7 @@ namespace ip { class Hls : public virtual Core { public: - virtual bool init() override { + bool init() override { auto ®isters = addressTranslations.at(registerMemory); controlRegister = reinterpret_cast( @@ -91,7 +91,7 @@ class Hls : public virtual Core { static constexpr const char *registerMemory = "Reg"; - virtual std::list getMemoryBlocks() const { + std::list getMemoryBlocks() const override { return {registerMemory}; } diff --git a/fpga/include/villas/fpga/ips/i2c.hpp b/fpga/include/villas/fpga/ips/i2c.hpp index b90f34fac..91f53d2e8 100644 --- a/fpga/include/villas/fpga/ips/i2c.hpp +++ b/fpga/include/villas/fpga/ips/i2c.hpp @@ -31,11 +31,11 @@ class I2c : public Node { friend class I2cFactory; I2c(); - virtual ~I2c(); - virtual bool init() override; - virtual bool check() override; - virtual bool reset() override; - virtual bool stop() override; + ~I2c() override; + bool init() override; + bool check() override; + bool reset() override; + bool stop() override; bool write(u8 address, std::vector &data); bool read(u8 address, std::vector &data, size_t max_read); bool readRegister(u8 address, u8 reg, std::vector &data, size_t max_read); @@ -93,7 +93,7 @@ class I2c : public Node { bool polling; std::unique_ptr switchInstance; - std::list getMemoryBlocks() const { + std::list getMemoryBlocks() const override { return {registerMemory}; } // assumes hwLock is locked @@ -104,21 +104,21 @@ class I2c : public Node { class I2cFactory : NodeFactory { public: - virtual std::string getName() const { return "i2c"; } + std::string getName() const override { return "i2c"; } - virtual std::string getDescription() const { return "Xilinx's AXI4 IIC IP"; } + std::string getDescription() const override { return "Xilinx's AXI4 IIC IP"; } private: - virtual Vlnv getCompatibleVlnv() const { + Vlnv getCompatibleVlnv() const override { return Vlnv("xilinx.com:ip:axi_iic:"); } // Create a concrete IP instance - Core *make() const { return new I2c; }; + Core *make() const override { return new I2c; }; protected: - virtual void parse(Core &ip, json_t *json) override; - virtual void configurePollingMode(Core &ip, PollingMode mode) override { + void parse(Core &ip, json_t *json) override; + void configurePollingMode(Core &ip, PollingMode mode) override { dynamic_cast(ip).polling = (mode == POLL); } }; diff --git a/fpga/include/villas/fpga/ips/intc.hpp b/fpga/include/villas/fpga/ips/intc.hpp index af3eba15c..cb459d989 100644 --- a/fpga/include/villas/fpga/ips/intc.hpp +++ b/fpga/include/villas/fpga/ips/intc.hpp @@ -22,10 +22,10 @@ class InterruptController : public Core { using IrqMaskType = uint32_t; static constexpr int maxIrqs = 32; - virtual ~InterruptController(); + ~InterruptController() override; - virtual bool init() override; - virtual bool stop() override; + bool init() override; + bool stop() override; virtual bool enableInterrupt(IrqMaskType mask, bool polling); bool enableInterrupt(const IrqPort &irq, bool polling) { @@ -47,7 +47,7 @@ class InterruptController : public Core { std::shared_ptr vfioDevice = nullptr; - std::list getMemoryBlocks() const { + std::list getMemoryBlocks() const override { return {registerMemory}; } diff --git a/fpga/include/villas/fpga/ips/pcie.hpp b/fpga/include/villas/fpga/ips/pcie.hpp index 85960bf8d..c82a45b2d 100644 --- a/fpga/include/villas/fpga/ips/pcie.hpp +++ b/fpga/include/villas/fpga/ips/pcie.hpp @@ -22,7 +22,7 @@ class AxiPciExpressBridge : public Core { public: friend class AxiPciExpressBridgeFactory; - virtual bool init() override; + bool init() override; protected: virtual const char *getAxiInterfaceName() { return "M_AXI"; }; @@ -44,42 +44,44 @@ class AxiPciExpressBridge : public Core { class XDmaBridge : public AxiPciExpressBridge { protected: - virtual const char *getAxiInterfaceName() { return "M_AXI_B"; }; + const char *getAxiInterfaceName() override { return "M_AXI_B"; }; }; class AxiPciExpressBridgeFactory : CoreFactory { public: - virtual std::string getName() const { return "pcie"; } + std::string getName() const override { return "pcie"; } - virtual std::string getDescription() const { + std::string getDescription() const override { return "Xilinx's AXI-PCIe Bridge"; } private: - virtual Vlnv getCompatibleVlnv() const { + Vlnv getCompatibleVlnv() const override { return Vlnv("xilinx.com:ip:axi_pcie:"); } // Create a concrete IP instance - Core *make() const { return new AxiPciExpressBridge; }; + Core *make() const override { return new AxiPciExpressBridge; }; protected: - virtual void parse(Core &, json_t *) override; + void parse(Core &, json_t *) override; }; class XDmaBridgeFactory : public AxiPciExpressBridgeFactory { public: - virtual std::string getDescription() const { + std::string getDescription() const override { return "Xilinx's XDMA IP configured as AXI-PCIe Bridge"; } private: - virtual Vlnv getCompatibleVlnv() const { return Vlnv("xilinx.com:ip:xdma:"); } + Vlnv getCompatibleVlnv() const override { + return Vlnv("xilinx.com:ip:xdma:"); + } // Create a concrete IP instance - Core *make() const { return new XDmaBridge; }; + Core *make() const override { return new XDmaBridge; }; }; } // namespace ip diff --git a/fpga/include/villas/fpga/ips/register.hpp b/fpga/include/villas/fpga/ips/register.hpp index 18657d7ee..69f1bd065 100644 --- a/fpga/include/villas/fpga/ips/register.hpp +++ b/fpga/include/villas/fpga/ips/register.hpp @@ -16,9 +16,9 @@ namespace ip { class Register : public Node { public: Register(); - virtual ~Register(); - virtual bool init() override; - virtual bool check() override; + ~Register() override; + bool init() override; + bool check() override; void setRegister(size_t reg, uint32_t value); void setRegister(size_t reg, float value); uint32_t getRegister(size_t reg); diff --git a/fpga/include/villas/fpga/ips/rtds.hpp b/fpga/include/villas/fpga/ips/rtds.hpp index 5168c0025..e14085a75 100644 --- a/fpga/include/villas/fpga/ips/rtds.hpp +++ b/fpga/include/villas/fpga/ips/rtds.hpp @@ -18,17 +18,19 @@ class RtdsGtfpga : public Node { static constexpr const char *masterPort = "m_axis"; static constexpr const char *slavePort = "s_axis"; - virtual void dump() override; + void dump() override; double getDt(); - std::list getMemoryBlocks() const { return {registerMemory}; } + std::list getMemoryBlocks() const override { + return {registerMemory}; + } - const StreamVertex &getDefaultSlavePort() const { + const StreamVertex &getDefaultSlavePort() const override { return getSlavePort(slavePort); } - const StreamVertex &getDefaultMasterPort() const { + const StreamVertex &getDefaultMasterPort() const override { return getMasterPort(masterPort); } diff --git a/fpga/include/villas/fpga/ips/rtds2gpu.hpp b/fpga/include/villas/fpga/ips/rtds2gpu.hpp index 508be3b7f..01af005df 100644 --- a/fpga/include/villas/fpga/ips/rtds2gpu.hpp +++ b/fpga/include/villas/fpga/ips/rtds2gpu.hpp @@ -30,11 +30,11 @@ class Rtds2Gpu : public Node, public Hls { public: friend class Rtds2GpuFactory; - virtual bool init() override; + bool init() override; void dump(spdlog::level::level_enum logLevel = spdlog::level::info); - virtual void dump() override { dump(spdlog::level::info); } + void dump() override { dump(spdlog::level::info); } bool startOnce(const MemoryBlock &mem, size_t frameSize, size_t dataOffset, size_t doorbellOffset); @@ -49,11 +49,11 @@ class Rtds2Gpu : public Node, public Hls { void doorbellReset(uint32_t &doorbellRegister) const { doorbellRegister = 0; } - std::list getMemoryBlocks() const { + std::list getMemoryBlocks() const override { return {registerMemory}; } - const StreamVertex &getDefaultSlavePort() const { + const StreamVertex &getDefaultSlavePort() const override { return getSlavePort(rtdsInputStreamPort); } diff --git a/fpga/include/villas/fpga/ips/switch.hpp b/fpga/include/villas/fpga/ips/switch.hpp index c55a4af56..a186ce26b 100644 --- a/fpga/include/villas/fpga/ips/switch.hpp +++ b/fpga/include/villas/fpga/ips/switch.hpp @@ -24,10 +24,10 @@ class AxiStreamSwitch : public Node { public: friend class AxiStreamSwitchFactory; - virtual bool init() override; + bool init() override; bool connectInternal(const std::string &slavePort, - const std::string &masterPort); + const std::string &masterPort) override; void printConfig() const; @@ -38,7 +38,7 @@ class AxiStreamSwitch : public Node { static constexpr char registerMemory[] = "Reg"; - std::list getMemoryBlocks() const { + std::list getMemoryBlocks() const override { return {registerMemory}; } @@ -51,22 +51,22 @@ class AxiStreamSwitch : public Node { class AxiStreamSwitchFactory : NodeFactory { public: - virtual std::string getName() const { return "switch"; } + std::string getName() const override { return "switch"; } - virtual std::string getDescription() const { + std::string getDescription() const override { return "Xilinx's AXI4-Stream switch"; } private: - virtual Vlnv getCompatibleVlnv() const { + Vlnv getCompatibleVlnv() const override { return Vlnv("xilinx.com:ip:axis_switch:"); } // Create a concrete IP instance - Core *make() const { return new AxiStreamSwitch; }; + Core *make() const override { return new AxiStreamSwitch; }; protected: - virtual void parse(Core &, json_t *) override; + void parse(Core &, json_t *) override; }; } // namespace ip diff --git a/fpga/include/villas/fpga/ips/timer.hpp b/fpga/include/villas/fpga/ips/timer.hpp index 1b57d6049..9ea377e6f 100644 --- a/fpga/include/villas/fpga/ips/timer.hpp +++ b/fpga/include/villas/fpga/ips/timer.hpp @@ -25,7 +25,7 @@ class Timer : public Core { friend class TimerFactory; public: - virtual bool init() override; + bool init() override; bool start(uint32_t ticks); bool wait(); @@ -38,7 +38,7 @@ class Timer : public Core { static constexpr uint32_t getFrequency() { return FPGA_AXI_HZ; } private: - std::list getMemoryBlocks() const { + std::list getMemoryBlocks() const override { return {registerMemory}; } diff --git a/fpga/include/villas/fpga/ips/zynq.hpp b/fpga/include/villas/fpga/ips/zynq.hpp index f21894e2c..c07bcbd2b 100644 --- a/fpga/include/villas/fpga/ips/zynq.hpp +++ b/fpga/include/villas/fpga/ips/zynq.hpp @@ -17,26 +17,26 @@ class Zynq : public Core { public: friend class ZynqFactory; - virtual bool init() override; + bool init() override; }; class ZynqFactory : CoreFactory { public: - virtual std::string getName() const { return "Zynq"; } + std::string getName() const override { return "Zynq"; } - virtual std::string getDescription() const { return "Zynq based fpga"; } + std::string getDescription() const override { return "Zynq based fpga"; } private: - virtual Vlnv getCompatibleVlnv() const { + Vlnv getCompatibleVlnv() const override { return Vlnv("xilinx.com:ip:zynq_ultra_ps_e:"); } // Create a concrete IP instance - Core *make() const { return new Zynq; }; + Core *make() const override { return new Zynq; }; protected: - virtual void parse(Core &, json_t *) override; + void parse(Core &, json_t *) override; }; } /* namespace ip */ diff --git a/fpga/include/villas/fpga/json_parser.hpp b/fpga/include/villas/fpga/json_parser.hpp index 8273fd589..cc3c7a888 100644 --- a/fpga/include/villas/fpga/json_parser.hpp +++ b/fpga/include/villas/fpga/json_parser.hpp @@ -8,12 +8,14 @@ #pragma once -#include #include #include #include +#include +#include + class JsonParser { private: inline static auto logger = villas::Log::get("Json Parser"); @@ -27,13 +29,13 @@ class JsonParser { JsonParser(const std::string &configFilePath) { FILE *f = fopen(configFilePath.c_str(), "r"); if (!f) - throw RuntimeError("Cannot open config file: {}", configFilePath); + throw villas::RuntimeError("Cannot open config file: {}", configFilePath); this->json = json_loadf(f, 0, nullptr); if (!json) { logger->error("Cannot parse JSON config"); fclose(f); - throw RuntimeError("Cannot parse JSON config"); + throw villas::RuntimeError("Cannot parse JSON config"); } fclose(f); diff --git a/fpga/include/villas/fpga/node.hpp b/fpga/include/villas/fpga/node.hpp index 2224cbc34..2afc60c4e 100644 --- a/fpga/include/villas/fpga/node.hpp +++ b/fpga/include/villas/fpga/node.hpp @@ -138,23 +138,23 @@ class NodeFactory : public CoreFactory { public: using CoreFactory::CoreFactory; - virtual void parse(Core &, json_t *); + void parse(Core &, json_t *) override; }; template class NodePlugin : public NodeFactory { public: - virtual std::string getName() const { return name; } + std::string getName() const override { return name; } - virtual std::string getDescription() const { return desc; } + std::string getDescription() const override { return desc; } private: // Get a VLNV identifier for which this IP / Node type can be used. - virtual Vlnv getCompatibleVlnv() const { return Vlnv(vlnv); } + Vlnv getCompatibleVlnv() const override { return Vlnv(vlnv); } // Create a concrete IP instance - Core *make() const { return new T; } + Core *make() const override { return new T; } }; } // namespace ip diff --git a/fpga/include/villas/fpga/pcie_card.hpp b/fpga/include/villas/fpga/pcie_card.hpp index 1583ed7de..030b60ae9 100644 --- a/fpga/include/villas/fpga/pcie_card.hpp +++ b/fpga/include/villas/fpga/pcie_card.hpp @@ -34,7 +34,7 @@ class PCIeCardFactory; class PCIeCard : public Card { public: - ~PCIeCard(); + ~PCIeCard() override; bool init(); @@ -73,13 +73,13 @@ class PCIeCardFactory : public plugin::Plugin { return villas::Log::get("pcie:card:factory"); } - virtual std::string getName() const { return "pcie"; } + std::string getName() const override { return "pcie"; } - virtual std::string getDescription() const { + std::string getDescription() const override { return "Xilinx PCIe FPGA cards"; } - virtual std::string getType() const { return "card"; } + std::string getType() const override { return "card"; } }; } // namespace fpga diff --git a/fpga/include/villas/fpga/platform_card.hpp b/fpga/include/villas/fpga/platform_card.hpp index cffcf1c8c..24d637d84 100644 --- a/fpga/include/villas/fpga/platform_card.hpp +++ b/fpga/include/villas/fpga/platform_card.hpp @@ -25,7 +25,7 @@ class PlatformCard : public Card { public: PlatformCard(std::shared_ptr vfioContainer); - ~PlatformCard(){}; + ~PlatformCard() override{}; std::vector core_connections; diff --git a/fpga/include/villas/fpga/utils.hpp b/fpga/include/villas/fpga/utils.hpp index 514e05768..75f2cd15a 100644 --- a/fpga/include/villas/fpga/utils.hpp +++ b/fpga/include/villas/fpga/utils.hpp @@ -81,6 +81,8 @@ class BufferedSampleFormatter { currentBufLoc = 0; } + virtual ~BufferedSampleFormatter() {} + protected: std::vector buf; const size_t bufSamples; @@ -101,7 +103,7 @@ class BufferedSampleFormatterShort : public BufferedSampleFormatter { BufferedSampleFormatterShort(size_t bufSizeInSamples) : BufferedSampleFormatter(bufSizeInSamples, formatStringSize){}; - virtual void format(float value) override { + void format(float value) override { size_t chars; if ((chars = std::snprintf(nextBufPos(), formatStringSize + 1, formatString, value)) > (int)formatStringSize) { @@ -122,7 +124,7 @@ class BufferedSampleFormatterLong : public BufferedSampleFormatter { : BufferedSampleFormatter(bufSizeInSamples, formatStringSize), sampleCnt(0){}; - virtual void format(float value) override { + void format(float value) override { if (std::snprintf(nextBufPos(), formatStringSize + 1, formatString, sampleCnt, value) > (int)formatStringSize) { throw RuntimeError("Output buffer too small"); diff --git a/fpga/lib/card.cpp b/fpga/lib/card.cpp index bb100d1bd..72a32b090 100644 --- a/fpga/lib/card.cpp +++ b/fpga/lib/card.cpp @@ -110,7 +110,7 @@ bool Card::mapMemoryBlock(const std::shared_ptr block) { auto translationFromProcess = mm.getTranslationFromProcess(addrSpaceId); uintptr_t processBaseAddr = translationFromProcess.getLocalAddr(0); - uintptr_t iovaAddr = + uintptr_t const iovaAddr = vfioContainer->memoryMap(processBaseAddr, UINTPTR_MAX, block->getSize()); if (iovaAddr == UINTPTR_MAX) { @@ -140,7 +140,7 @@ void CardFactory::loadIps(std::shared_ptr card, json_t *json_ips, } if (!searchPath.empty()) { - std::filesystem::path json_ips_path = + std::filesystem::path const json_ips_path = searchPath / json_string_value(json_ips); logger->debug("searching for FPGA IP cors config at {}", json_ips_path.string()); @@ -184,8 +184,9 @@ void CardFactory::loadSwitch(std::shared_ptr card, json_t *json_paths) { const char *from, *to; int reverse = 0; - int ret = json_unpack_ex(json_path, &err, 0, "{ s: s, s: s, s?: b }", - "from", &from, "to", &to, "reverse", &reverse); + int const ret = + json_unpack_ex(json_path, &err, 0, "{ s: s, s: s, s?: b }", "from", + &from, "to", &to, "reverse", &reverse); if (ret != 0) throw ConfigError(json_path, err, "", "Cannot parse switch path config"); diff --git a/fpga/lib/core.cpp b/fpga/lib/core.cpp index 70f17c131..2abd5b4b5 100644 --- a/fpga/lib/core.cpp +++ b/fpga/lib/core.cpp @@ -48,7 +48,7 @@ std::list CoreFactory::parseIpIdentifier(json_t *json_ips) { const char *vlnv; json_error_t err; - int ret = json_unpack_ex(json_ip, &err, 0, "{ s: s }", "vlnv", &vlnv); + int const ret = json_unpack_ex(json_ip, &err, 0, "{ s: s }", "vlnv", &vlnv); if (ret != 0) throw ConfigError(json_ip, err, "", "IP {} has no VLNV", ipName); @@ -156,7 +156,7 @@ CoreFactory::configureIps(std::list orderedIps, json_t *json_ips, json_t *json_parameters = json_object_get(json_ip, "parameters"); if (json_is_object(json_parameters)) { json_int_t c_baseaddr = 0; - int baseaddress_found = + int const baseaddress_found = json_unpack(json_parameters, "{ s?: I }", "c_baseaddr", &c_baseaddr); if (baseaddress_found == 0) ip->baseaddr = c_baseaddr; @@ -247,9 +247,9 @@ CoreFactory::configureIps(std::list orderedIps, json_t *json_ips, json_int_t base, high, size; json_error_t err; - int ret = json_unpack_ex(json_block, &err, 0, - "{ s: I, s: I, s: I }", "baseaddr", &base, - "highaddr", &high, "size", &size); + int const ret = json_unpack_ex( + json_block, &err, 0, "{ s: I, s: I, s: I }", "baseaddr", &base, + "highaddr", &high, "size", &size); if (ret != 0) throw ConfigError( json_block, err, "", "Cannot parse address block {}/{}/{}/{}", @@ -343,16 +343,16 @@ std::list> CoreFactory::make(Card *card, throw RuntimeError("IP list of card {} already contains IPs.", card->name); } - std::list allIps = + std::list const allIps = parseIpIdentifier(json_ips); // All IPs available in config - std::list filteredIps = filterIps( + std::list const filteredIps = filterIps( allIps, card->ignored_ip_names); // Remove ips on ignorelist in .conf - std::list orderedIps = + std::list const orderedIps = reorderIps(filteredIps); // IPs ordered in initialization order - std::list> configuredIps = + std::list> const configuredIps = configureIps(orderedIps, json_ips, card); // Successfully configured IPs /* If Platform then connect the ips via vfio diff --git a/fpga/lib/core_connection.cpp b/fpga/lib/core_connection.cpp index fd4ffba07..fce6c74da 100644 --- a/fpga/lib/core_connection.cpp +++ b/fpga/lib/core_connection.cpp @@ -49,15 +49,15 @@ CoreConnection::from(std::shared_ptr ip, void CoreConnection::add_to_memorygraph() { device_connection.addToMemorygraph(); - for (std::string memory_block : ip->getMemoryBlocks()) { + for (std::string const &memory_block : ip->getMemoryBlocks()) { auto &mm = MemoryManager::get(); // 16 bit width => 2^16 = 65536 const size_t ip_mem_size = 65536; - size_t srcVertexId = + size_t const srcVertexId = mm.findAddressSpace(device_connection.vfio_device->getName()); - std::string taget_address_space_name = + std::string const taget_address_space_name = ip->getInstanceName() + "/" + memory_block; size_t targetVertexId; targetVertexId = mm.findAddressSpace(taget_address_space_name); diff --git a/fpga/lib/dma.cpp b/fpga/lib/dma.cpp index 6ea1e0318..0b8e60cb9 100644 --- a/fpga/lib/dma.cpp +++ b/fpga/lib/dma.cpp @@ -5,6 +5,7 @@ * SPDX-License-Identifier: Apache-2.0 */ +#include #include #include @@ -31,11 +32,11 @@ struct villasfpga_memory_t { }; villasfpga_handle villasfpga_init(const char *configFile) { - std::string fpgaName = "vc707"; + std::string const fpgaName = "vc707"; std::string connectStr = "3<->pipe"; - std::string outputFormat = "short"; - bool dumpGraph = false; - bool dumpAuroraChannels = true; + std::string const outputFormat = "short"; + bool const dumpGraph = false; + bool const dumpAuroraChannels = true; try { // Logging setup Log::getInstance().setLevel(spdlog::level::debug); @@ -47,7 +48,7 @@ villasfpga_handle villasfpga_init(const char *configFile) { return nullptr; } - auto handle = new villasfpga_handle_t; + auto handle = std::make_unique(); handle->card = fpga::setupFpgaCard(configFile, fpgaName); if (dumpGraph) { @@ -68,7 +69,7 @@ villasfpga_handle villasfpga_init(const char *configFile) { return nullptr; } - return handle; + return handle.release(); } catch (const RuntimeError &e) { logger->error("Error: {}", e.what()); return nullptr; @@ -81,7 +82,9 @@ villasfpga_handle villasfpga_init(const char *configFile) { } } -void villasfpga_destroy(villasfpga_handle handle) { delete handle; } +void villasfpga_destroy(villasfpga_handle handle) { + std::unique_ptr{handle}; +} int villasfpga_alloc(villasfpga_handle handle, villasfpga_memory *mem, size_t size) { diff --git a/fpga/lib/ips/bram.cpp b/fpga/lib/ips/bram.cpp index 4f2032542..bd37ada77 100644 --- a/fpga/lib/ips/bram.cpp +++ b/fpga/lib/ips/bram.cpp @@ -17,7 +17,7 @@ void BramFactory::parse(Core &ip, json_t *cfg) { auto &bram = dynamic_cast(ip); json_error_t err; - int ret = json_unpack_ex(cfg, &err, 0, "{ s: i }", "size", &bram.size); + int const ret = json_unpack_ex(cfg, &err, 0, "{ s: i }", "size", &bram.size); if (ret != 0) throw ConfigError(cfg, err, "", "Cannot parse BRAM config"); } diff --git a/fpga/lib/ips/dino.cpp b/fpga/lib/ips/dino.cpp index a3df87124..7f8d34f86 100644 --- a/fpga/lib/ips/dino.cpp +++ b/fpga/lib/ips/dino.cpp @@ -153,8 +153,9 @@ void DinoAdc::setRegisterConfig(std::shared_ptr reg, constexpr size_t dinoRegisterTimerPreThresh = 8; // -1 because the timer counts from 0 to the value set in the register. Should really be fixed in hardware. - uint32_t dinoTimerVal = static_cast(dinoClk / sampleRate) - 1; - uint32_t dinoDacDelayCycles = static_cast(dinoClk * dinoDacDelay); + uint32_t const dinoTimerVal = static_cast(dinoClk / sampleRate) - 1; + uint32_t const dinoDacDelayCycles = + static_cast(dinoClk * dinoDacDelay); double rateError = dinoClk / (dinoTimerVal + 1) - sampleRate; // Timer value for generating ADC trigger signal @@ -255,7 +256,7 @@ Dino::Gain DinoDac::getGain() { throw RuntimeError("I2C device not set"); } i2cdev->getSwitch().setAndLockChannel(i2c_channel); - IoextPorts ioext = getIoextOut(); + IoextPorts const ioext = getIoextOut(); auto ret = static_cast((ioext.fields.gain_msb << 1) | ioext.fields.gain_lsb); i2cdev->getSwitch().unlockChannel(); @@ -268,7 +269,7 @@ void DinoFactory::parse(Core &ip, json_t *cfg) { auto &dino = dynamic_cast(ip); json_error_t err; int i2c_channel; - int ret = + int const ret = json_unpack_ex(cfg, &err, 0, "{ s: i }", "i2c_channel", &i2c_channel); if (ret != 0) { throw ConfigError(cfg, err, "", "Failed to parse Dino configuration"); diff --git a/fpga/lib/ips/dma.cpp b/fpga/lib/ips/dma.cpp index 11134c306..68a031a8e 100644 --- a/fpga/lib/ips/dma.cpp +++ b/fpga/lib/ips/dma.cpp @@ -304,9 +304,9 @@ bool Dma::writeScatterGatherFast() { BdSts &= ~XAXIDMA_BD_STS_COMPLETE_MASK; XAxiDma_BdWrite(CurBdPtr, XAXIDMA_BD_STS_OFFSET, BdSts); - uintptr_t tdesc = ((uintptr_t)txRing->HwTail + - (txRing->FirstBdPhysAddr - txRing->FirstBdAddr)) & - XAXIDMA_DESC_LSB_MASK; + uintptr_t const tdesc = ((uintptr_t)txRing->HwTail + + (txRing->FirstBdPhysAddr - txRing->FirstBdAddr)) & + XAXIDMA_DESC_LSB_MASK; XAxiDma_WriteReg(txRing->ChanBase, XAXIDMA_TDESC_OFFSET, tdesc); hwWriteLock.unlock(); @@ -417,9 +417,9 @@ bool Dma::readScatterGatherFast() { BdSts &= ~XAXIDMA_BD_STS_COMPLETE_MASK; XAxiDma_BdWrite(CurBdPtr, XAXIDMA_BD_STS_OFFSET, BdSts); - uintptr_t tdesc = ((uintptr_t)rxRing->HwTail + - (rxRing->FirstBdPhysAddr - rxRing->FirstBdAddr)) & - XAXIDMA_DESC_LSB_MASK; + uintptr_t const tdesc = ((uintptr_t)rxRing->HwTail + + (rxRing->FirstBdPhysAddr - rxRing->FirstBdAddr)) & + XAXIDMA_DESC_LSB_MASK; XAxiDma_WriteReg(rxRing->ChanBase, XAXIDMA_TDESC_OFFSET, tdesc); hwReadLock.unlock(); @@ -651,7 +651,7 @@ Dma::Completion Dma::readCompleteScatterGather() { logger->warn("Interrupt error or timeout: {}", intrs); // Free all RX BDs for future transmission. - int bds = XAxiDma_BdRingFromHw(rxRing, XAXIDMA_ALL_BDS, &bd); + int const bds = XAxiDma_BdRingFromHw(rxRing, XAXIDMA_ALL_BDS, &bd); XAxiDma_BdRingFree(rxRing, bds, bd); hwReadLock.unlock(); @@ -922,7 +922,7 @@ void DmaFactory::parse(Core &ip, json_t *cfg) { dma.xConfig.SgLengthWidth = 14; json_error_t err; - int ret = json_unpack_ex( + int const ret = json_unpack_ex( cfg, &err, 0, "{ s: { s?: i, s?: i, s?: i, s?: i, s?: i, s?: i, s?: i, s?: i, s?: i, " "s?: i, s?: i, s?: i, s?: i } }", diff --git a/fpga/lib/ips/emc.cpp b/fpga/lib/ips/emc.cpp index a4b34f9d5..88e82af56 100644 --- a/fpga/lib/ips/emc.cpp +++ b/fpga/lib/ips/emc.cpp @@ -84,7 +84,7 @@ bool EMC::flash(uint32_t offset, const std::string &filename) { // Based on xilflash_readwrite_example.c bool EMC::flash(uint32_t offset, uint32_t length, uint8_t *data) { int ret = XST_FAILURE; - uint32_t start = offset; + uint32_t const start = offset; /* Reset the Flash Device. This clears the ret registers and puts * the device in Read mode. */ diff --git a/fpga/lib/ips/i2c.cpp b/fpga/lib/ips/i2c.cpp index 75ec4dbe3..42d389a44 100644 --- a/fpga/lib/ips/i2c.cpp +++ b/fpga/lib/ips/i2c.cpp @@ -107,7 +107,7 @@ void I2c::driverWriteBlocking(u8 *dataPtr, size_t size) { // We need to wait for several interrupts as sending the stop condition involves generating // multiple interrupts before the transmission is complete. while (transmitIntrs == 0 && intrRetries > 0) { - ssize_t intrs = irqs[i2cInterrupt].irqController->waitForInterrupt( + ssize_t const intrs = irqs[i2cInterrupt].irqController->waitForInterrupt( irqs[i2cInterrupt].num); if (intrs == -1) { break; @@ -147,7 +147,7 @@ void I2c::driverReadBlocking(u8 *dataPtr, size_t max_read) { } } while (ret == XST_IIC_BUS_BUSY && --bbRetries >= 0); while (receiveIntrs == 0 && intrRetries > 0) { - ssize_t intrs = irqs[i2cInterrupt].irqController->waitForInterrupt( + ssize_t const intrs = irqs[i2cInterrupt].irqController->waitForInterrupt( irqs[i2cInterrupt].num); if (intrs == -1) { break; @@ -175,7 +175,7 @@ void I2c::waitForBusNotBusy() { //Deactivate BusNotBusy interrupt XIic_WriteIier(xIic.BaseAddress, XIic_ReadIier(xIic.BaseAddress) & ~(XIIC_INTR_BNB_MASK)); - uint32_t clear = XIIC_INTR_BNB_MASK; + uint32_t const clear = XIIC_INTR_BNB_MASK; XIic_WriteIisr(xIic.BaseAddress, clear); if (retries == 0) { throw RuntimeError("I2C bus stayed busy after 10 interrupts"); @@ -317,17 +317,17 @@ void I2cFactory::parse(Core &ip, json_t *cfg) { char *component_name = nullptr; json_error_t err; - int ret = json_unpack_ex(cfg, &err, 0, "{ s: { s?: i, s?: i, s?: i, s?: s} }", - "parameters", "c_iic_freq", &i2c_frequency, - "c_ten_bit_adr", &i2c.xConfig.Has10BitAddr, - "c_gpo_width", &i2c.xConfig.GpOutWidth, - "component_name", &component_name); + int const ret = json_unpack_ex( + cfg, &err, 0, "{ s: { s?: i, s?: i, s?: i, s?: s} }", "parameters", + "c_iic_freq", &i2c_frequency, "c_ten_bit_adr", &i2c.xConfig.Has10BitAddr, + "c_gpo_width", &i2c.xConfig.GpOutWidth, "component_name", + &component_name); if (ret != 0) { throw ConfigError(cfg, err, "", "Failed to parse DMA configuration for {}", ip.getInstanceName()); } if (component_name != nullptr) { - char last_letter = component_name[strlen(component_name) - 1]; + char const last_letter = component_name[strlen(component_name) - 1]; if (last_letter >= '0' && last_letter <= '9') { i2c.xConfig.DeviceId = last_letter - '0'; } else { diff --git a/fpga/lib/ips/intc.cpp b/fpga/lib/ips/intc.cpp index 4f3fd035e..c04a5b3aa 100644 --- a/fpga/lib/ips/intc.cpp +++ b/fpga/lib/ips/intc.cpp @@ -29,7 +29,7 @@ bool InterruptController::init() { this->vfioDevice = pciecard->vfioDevice; const uintptr_t base = getBaseAddr(registerMemory); - kernel::vfio::Device::IrqVectorInfo irq_vector = {0}; + kernel::vfio::Device::IrqVectorInfo irq_vector = {{0}}; irq_vector.numFds = this->vfioDevice->pciMsiInit(irq_vector.eventFds); irq_vector.automask = true; irq_vectors.push_back(irq_vector); @@ -45,7 +45,7 @@ bool InterruptController::init() { for (size_t i = 0; i < irq_vector.numFds; i++) { // Try pinning to core - int ret = kernel::setIRQAffinity(nos[i], pciecard->affinity, nullptr); + int const ret = kernel::setIRQAffinity(nos[i], pciecard->affinity, nullptr); switch (ret) { case 0: @@ -114,7 +114,7 @@ bool InterruptController::enableInterrupt(InterruptController::IrqMaskType mask, bool InterruptController::disableInterrupt( InterruptController::IrqMaskType mask) { const uintptr_t base = getBaseAddr(registerMemory); - uint32_t ier = XIntc_In32(base + XIN_IER_OFFSET); + uint32_t const ier = XIntc_In32(base + XIN_IER_OFFSET); XIntc_Out32(base + XIN_IER_OFFSET, ier & ~mask); @@ -127,7 +127,8 @@ ssize_t InterruptController::waitForInterrupt(int irq) { if (this->polling[irq]) { const uintptr_t base = getBaseAddr(registerMemory); - uint32_t isr, mask = 1 << irq; + const uint32_t mask = 1 << irq; + uint32_t isr; do { // Poll status register @@ -171,8 +172,8 @@ ssize_t InterruptController::waitForInterrupt(int irq) { irqSet.index = 0; irqSet.start = irq; irqSet.count = 1; - int ret = ioctl(this->vfioDevice->getFileDescriptor(), - VFIO_DEVICE_SET_IRQS, &irqSet); + int const ret = ioctl(this->vfioDevice->getFileDescriptor(), + VFIO_DEVICE_SET_IRQS, &irqSet); if (ret < 0) { logger->error("Failed to unmask IRQ {}", 0); } diff --git a/fpga/lib/ips/pcie.cpp b/fpga/lib/ips/pcie.cpp index 0d158f22b..90b15f835 100644 --- a/fpga/lib/ips/pcie.cpp +++ b/fpga/lib/ips/pcie.cpp @@ -115,15 +115,15 @@ void AxiPciExpressBridgeFactory::parse(Core &ip, json_t *cfg) { unsigned int translation; json_error_t err; - int ret = json_unpack_ex(json_bar, &err, 0, "{ s: i }", "translation", - &translation); + int const ret = json_unpack_ex(json_bar, &err, 0, "{ s: i }", + "translation", &translation); if (ret != 0) throw ConfigError(json_bar, err, "", "Cannot parse {}/{}", barType, bar_name); if (barType == "axi_bars") { json_int_t base, high, size; - int ret = + int const ret = json_unpack_ex(json_bar, &err, 0, "{ s: I, s: I, s: I }", "baseaddr", &base, "highaddr", &high, "size", &size); if (ret != 0) diff --git a/fpga/lib/ips/rtds2gpu/gpu2rtds.cpp b/fpga/lib/ips/rtds2gpu/gpu2rtds.cpp index 172953536..820a2b970 100644 --- a/fpga/lib/ips/rtds2gpu/gpu2rtds.cpp +++ b/fpga/lib/ips/rtds2gpu/gpu2rtds.cpp @@ -115,7 +115,7 @@ size_t Gpu2Rtds::getMaxFrameSize() { while (not registerStatusCtrl->status_ap_vld) ; - axilite_reg_status_t status = *registerStatus; + axilite_reg_status_t const status = *registerStatus; // logger->debug("(*registerStatus).max_frame_size: {}", (*registerStatus).max_frame_size); // logger->debug("status.max_frame_size: {}", status.max_frame_size); diff --git a/fpga/lib/ips/timer.cpp b/fpga/lib/ips/timer.cpp index 0af2e73a5..65e03f4e4 100644 --- a/fpga/lib/ips/timer.cpp +++ b/fpga/lib/ips/timer.cpp @@ -46,7 +46,8 @@ bool Timer::start(uint32_t ticks) { } bool Timer::wait() { - int count = irqs[irqName].irqController->waitForInterrupt(irqs[irqName]); + int const count = + irqs[irqName].irqController->waitForInterrupt(irqs[irqName]); irqs[irqName].irqController->disableInterrupt(irqs[irqName]); return (count == 1); diff --git a/fpga/lib/node.cpp b/fpga/lib/node.cpp index 43b57bf25..45db48be1 100644 --- a/fpga/lib/node.cpp +++ b/fpga/lib/node.cpp @@ -37,7 +37,7 @@ void NodeFactory::parse(Core &ip, json_t *cfg) { const char *role_raw, *target_raw, *name_raw; json_error_t err; - int ret = + int const ret = json_unpack_ex(json_port, &err, 0, "{ s: s, s: s, s: s }", "role", &role_raw, "target", &target_raw, "name", &name_raw); if (ret != 0) diff --git a/fpga/lib/pcie_card.cpp b/fpga/lib/pcie_card.cpp index ca8e3410a..93360b257 100644 --- a/fpga/lib/pcie_card.cpp +++ b/fpga/lib/pcie_card.cpp @@ -48,7 +48,7 @@ PCIeCardFactory::make(json_t *json_card, std::string card_name, json_t *ignored_ips_array = nullptr; json_error_t err; - int ret = json_unpack_ex( + int const ret = json_unpack_ex( json_card, &err, 0, "{ s: o, s?: i, s?: b, s?: s, s?: s, s?: b, s?: o, s?: o}", "ips", &json_ips, "affinity", &affinity, "do_reset", &do_reset, "slot", diff --git a/fpga/lib/platform_card.cpp b/fpga/lib/platform_card.cpp index ae7ade806..7a2076715 100644 --- a/fpga/lib/platform_card.cpp +++ b/fpga/lib/platform_card.cpp @@ -61,7 +61,7 @@ bool PlatformCard::mapMemoryBlock(const std::shared_ptr block) { auto translationFromProcess = mm.getTranslationFromProcess(addrSpaceId); uintptr_t processBaseAddr = translationFromProcess.getLocalAddr(0); - uintptr_t iovaAddr = + uintptr_t const iovaAddr = vfioContainer->memoryMap(processBaseAddr, UINTPTR_MAX, block->getSize()); if (iovaAddr == UINTPTR_MAX) { @@ -94,7 +94,7 @@ PlatformCardFactory::make(json_t *json_card, std::string card_name, // make sure the vfio container has the required modules kernel::loadModule("vfio_platform"); - CardParser parser(json_card); + CardParser const parser(json_card); auto card = std::make_shared(vc); card->name = std::string(card_name); diff --git a/fpga/lib/utils.cpp b/fpga/lib/utils.cpp index 62f144ec6..8b7179d63 100644 --- a/fpga/lib/utils.cpp +++ b/fpga/lib/utils.cpp @@ -240,7 +240,7 @@ fpga::createCard(json_t *config, const std::filesystem::path &searchPath, const char *interfaceName; json_error_t err; logger->info("Found config for FPGA card {}", card_name); - int ret = + int const ret = json_unpack_ex(config, &err, 0, "{s: s}", "interface", &interfaceName); if (ret) { throw ConfigError(config, err, "interface", diff --git a/fpga/src/villas-fpga-ctrl.cpp b/fpga/src/villas-fpga-ctrl.cpp index 05317524b..b17262a62 100644 --- a/fpga/src/villas-fpga-ctrl.cpp +++ b/fpga/src/villas-fpga-ctrl.cpp @@ -40,7 +40,7 @@ void writeToDmaFromStdIn(std::shared_ptr dma) { auto &alloc = villas::HostRam::getAllocator(); const std::shared_ptr block = alloc.allocateBlock(0x200 * sizeof(float)); - villas::MemoryAccessor mem = *block; + villas::MemoryAccessor const mem = *block; dma->makeAccesibleFromVA(block); logger->info("Please enter values to write to the device, separated by ';'"); @@ -61,7 +61,7 @@ void writeToDmaFromStdIn(std::shared_ptr dma) { } // Initiate write transfer - bool state = dma->write(*block, i * sizeof(float)); + bool const state = dma->write(*block, i * sizeof(float)); if (!state) logger->error("Failed to write to device"); @@ -79,7 +79,7 @@ void readFromDmaToStdOut( const std::shared_ptr block[] = { alloc.allocateBlock(0x200 * sizeof(uint32_t)), alloc.allocateBlock(0x200 * sizeof(uint32_t))}; - villas::MemoryAccessor mem[] = {*block[0], *block[1]}; + villas::MemoryAccessor const mem[] = {*block[0], *block[1]}; for (auto b : block) { dma->makeAccesibleFromVA(b); @@ -110,7 +110,7 @@ void readFromDmaToStdOut( int32_t ival = mem[cur][i]; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" - float fval = + float const fval = *((float *)(&ival)); // cppcheck-suppress invalidPointerCast #pragma GCC diagnostic pop formatter->format(fval); diff --git a/fpga/src/villas-fpga-pipe.cpp b/fpga/src/villas-fpga-pipe.cpp index 3aba1657a..70d94e7b0 100644 --- a/fpga/src/villas-fpga-pipe.cpp +++ b/fpga/src/villas-fpga-pipe.cpp @@ -91,7 +91,7 @@ int main(int argc, char *argv[]) { const std::shared_ptr block[] = { alloc.allocateBlock(0x200 * sizeof(uint32_t)), alloc.allocateBlock(0x200 * sizeof(uint32_t))}; - villas::MemoryAccessor mem[] = {*block[0], *block[1]}; + villas::MemoryAccessor const mem[] = {*block[0], *block[1]}; for (auto b : block) { dma->makeAccesibleFromVA(b); @@ -118,7 +118,7 @@ int main(int argc, char *argv[]) { } // Initiate write transfer - bool state = dma->write(*block[1], i * sizeof(int32_t)); + bool const state = dma->write(*block[1], i * sizeof(int32_t)); if (!state) logger->error("Failed to write to device"); diff --git a/fpga/tests/unit/dma.cpp b/fpga/tests/unit/dma.cpp index 6700266dd..4265653a7 100644 --- a/fpga/tests/unit/dma.cpp +++ b/fpga/tests/unit/dma.cpp @@ -44,7 +44,7 @@ Test(fpga, dma, .description = "DMA") { // Simple DMA can only transfer up to 4 kb due to PCIe page size burst // limitation - size_t len = 4 * (1 << 10); + size_t const len = 4 * (1 << 10); #if 0 // Allocate memory to use with DMA @@ -68,8 +68,8 @@ Test(fpga, dma, .description = "DMA") { alloc.allocateBlock(len); const std::shared_ptr dstBlock = alloc.allocateBlock(len); - villas::MemoryAccessor src(*srcBlock); - villas::MemoryAccessor dst(*dstBlock); + villas::MemoryAccessor const src(*srcBlock); + villas::MemoryAccessor const dst(*dstBlock); #endif // Make sure memory is accessible for DMA dma->makeAccesibleFromVA(srcBlock); diff --git a/fpga/tests/unit/logging.cpp b/fpga/tests/unit/logging.cpp index 11a085815..8f2bf63f3 100644 --- a/fpga/tests/unit/logging.cpp +++ b/fpga/tests/unit/logging.cpp @@ -30,7 +30,7 @@ struct criterion_prefix_data { }; static int format_msg(char *buf, size_t buflen, const char *msg, va_list args) { - int len = vsnprintf(buf, buflen, msg, args); + int const len = vsnprintf(buf, buflen, msg, args); // Strip new line char *nl = strchr(buf, '\n'); diff --git a/fpga/tests/unit/rtds.cpp b/fpga/tests/unit/rtds.cpp index b0c9e69f5..c30c9401d 100644 --- a/fpga/tests/unit/rtds.cpp +++ b/fpga/tests/unit/rtds.cpp @@ -34,12 +34,12 @@ Test(fpga, rtds, .description = "RTDS") { for (auto &ip : state.cards.front()->ips) { if (*ip == villas::fpga::Vlnv("acs.eonerc.rwth-aachen.de:user:rtds_axis:")) { - auto rtds = reinterpret_cast(ip.get()); + auto rtds = dynamic_cast(ip.get()); rtdsIps.push_back(rtds); } if (*ip == villas::fpga::Vlnv("xilinx.com:ip:axi_dma:")) { - auto dma = reinterpret_cast(ip.get()); + auto dma = dynamic_cast(ip.get()); dmaIps.push_back(dma); } } diff --git a/fpga/tests/unit/rtds_rtt.cpp b/fpga/tests/unit/rtds_rtt.cpp deleted file mode 100644 index 882f4c6ec..000000000 --- a/fpga/tests/unit/rtds_rtt.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/* RTDS AXI-Stream RTT unit test. - * - * Author: Steffen Vogel - * SPDX-FileCopyrightText: 2017 Steffen Vogel - * SPDX-License-Identifier: Apache-2.0 - */ - -#include - -#include -#include -#include -#include -#include - -extern struct fpga_card *card; - -// cppcheck-suppress unknownMacro -Test(fpga, rtds_rtt, .description = "RTDS: tight rtt") { - int ret; - struct fpga_ip *ip, *rtds; - struct dma_mem buf; - size_t recvlen; - - std::list rtdsIps; - std::list dmaIps; - - // Get IP cores - for (auto &ip : state.cards.front()->ips) { - if (*ip == - villas::fpga::Vlnv("acs.eonerc.rwth-aachen.de:user:rtds_axis:")) { - auto rtds = reinterpret_cast(ip.get()); - rtdsIps.push_back(rtds); - } - - if (*ip == villas::fpga::Vlnv("xilinx.com:ip:axi_dma:")) { - auto dma = reinterpret_cast(ip.get()); - dmaIps.push_back(dma); - } - } - - for (auto rtds : rtdsIps) { - for (auto dma : dmaIps) { - - rtds->connect - } - } - - ret = switch_connect(card->sw, rtds, ip); - cr_assert_eq(ret, 0, "Failed to configure switch"); - - ret = switch_connect(card->sw, ip, rtds); - cr_assert_eq(ret, 0, "Failed to configure switch"); - - ret = dma_alloc(ip, &buf, 0x100, 0); - cr_assert_eq(ret, 0, "Failed to allocate DMA memory"); - - while (1) { - - ret = dma_read(ip, buf.base_phys, buf.len); - cr_assert_eq(ret, 0, "Failed to start DMA read: %d", ret); - - ret = dma_read_complete(ip, NULL, &recvlen); - cr_assert_eq(ret, 0, "Failed to complete DMA read: %d", ret); - - ret = dma_write(ip, buf.base_phys, recvlen); - cr_assert_eq(ret, 0, "Failed to start DMA write: %d", ret); - - ret = dma_write_complete(ip, NULL, NULL); - cr_assert_eq(ret, 0, "Failed to complete DMA write: %d", ret); - } - - ret = switch_disconnect(card->sw, rtds, ip); - cr_assert_eq(ret, 0, "Failed to configure switch"); - - ret = switch_disconnect(card->sw, ip, rtds); - cr_assert_eq(ret, 0, "Failed to configure switch"); - - ret = dma_free(ip, &buf); - cr_assert_eq(ret, 0, "Failed to release DMA memory"); -} diff --git a/include/villas/api.hpp b/include/villas/api.hpp index b4a682865..be8b76e55 100644 --- a/include/villas/api.hpp +++ b/include/villas/api.hpp @@ -40,9 +40,7 @@ class Error : public RuntimeError { } template - Error(int c = HTTP_STATUS_INTERNAL_SERVER_ERROR, - const std::string &msg = "Invalid API request", - const char *fmt = nullptr, Args &&...args) + Error(int c, const std::string &msg, const char *fmt, Args &&...args) : RuntimeError(msg), code(c), json(fmt ? json_pack(fmt, std::forward(args)...) : nullptr) {} diff --git a/include/villas/api/request.hpp b/include/villas/api/request.hpp index 7330949fe..909413db5 100644 --- a/include/villas/api/request.hpp +++ b/include/villas/api/request.hpp @@ -103,7 +103,7 @@ class RequestFactory : public plugin::Plugin { virtual void init(Request *r) { r->logger = getLogger(); } - virtual std::string getType() const { return "api:request"; } + std::string getType() const override { return "api:request"; } virtual bool isHidden() const { return false; } }; @@ -117,7 +117,7 @@ class RequestPlugin : public RequestFactory { public: RequestPlugin() : RequestFactory(), regex(re) {} - virtual Request *make(Session *s) { + Request *make(Session *s) override { auto *r = new T(s); init(r); @@ -126,12 +126,12 @@ class RequestPlugin : public RequestFactory { } // Get plugin name - virtual std::string getName() const { return name; } + std::string getName() const override { return name; } // Get plugin description - virtual std::string getDescription() const { return desc; } + std::string getDescription() const override { return desc; } - virtual bool match(const std::string &uri, std::smatch &match) const { + bool match(const std::string &uri, std::smatch &match) const override { return std::regex_match(uri, match, regex); } }; diff --git a/include/villas/api/response.hpp b/include/villas/api/response.hpp index 2fc9e3ec3..350e28ace 100644 --- a/include/villas/api/response.hpp +++ b/include/villas/api/response.hpp @@ -65,9 +65,9 @@ class JsonResponse : public Response { JsonResponse(Session *s, int c, json_t *r) : Response(s, c, "application/json"), response(r) {} - virtual ~JsonResponse(); + ~JsonResponse() override; - virtual void encodeBody(); + void encodeBody() override; }; class ErrorResponse : public JsonResponse { diff --git a/include/villas/format.hpp b/include/villas/format.hpp index f313e2e8a..56f0fde18 100644 --- a/include/villas/format.hpp +++ b/include/villas/format.hpp @@ -127,7 +127,7 @@ class FormatFactory : public plugin::Plugin { virtual void init(Format *f) { f->logger = getLogger(); } - virtual std::string getType() const { return "format"; } + std::string getType() const override { return "format"; } virtual bool isHidden() const { return false; } }; @@ -138,7 +138,7 @@ class FormatPlugin : public FormatFactory { public: using FormatFactory::FormatFactory; - virtual Format *make() { + Format *make() override { auto *f = new T(flags); init(f); @@ -146,9 +146,9 @@ class FormatPlugin : public FormatFactory { return f; } - virtual std::string getName() const { return name; } + std::string getName() const override { return name; } - virtual std::string getDescription() const { return desc; } + std::string getDescription() const override { return desc; } }; } // namespace node diff --git a/include/villas/formats/villas_binary.hpp b/include/villas/formats/villas_binary.hpp index 700a6772b..f6642132b 100644 --- a/include/villas/formats/villas_binary.hpp +++ b/include/villas/formats/villas_binary.hpp @@ -60,7 +60,7 @@ class VillasBinaryFormatPlugin : public FormatFactory { } // Get plugin description - virtual std::string getDescription() const { + std::string getDescription() const override { std::stringstream ss; ss << "VILLAS binary network format"; diff --git a/include/villas/hook.hpp b/include/villas/hook.hpp index 69eb3f3a1..b0a731ba5 100644 --- a/include/villas/hook.hpp +++ b/include/villas/hook.hpp @@ -131,9 +131,9 @@ class SingleSignalHook : public Hook { SingleSignalHook(Path *p, Node *n, int fl, int prio, bool en = true) : Hook(p, n, fl, prio, en), signalIndex(0) {} - virtual void parse(json_t *json); + void parse(json_t *json) override; - virtual void prepare(); + void prepare() override; }; class MultiSignalHook : public Hook { @@ -145,11 +145,11 @@ class MultiSignalHook : public Hook { public: using Hook::Hook; - virtual void parse(json_t *json); + void parse(json_t *json) override; - virtual void prepare(); + void prepare() override; - virtual void check(); + void check() override; }; class LimitHook : public Hook { @@ -160,7 +160,7 @@ class LimitHook : public Hook { virtual void setRate(double rate, double maxRate = -1) = 0; - virtual void parse(json_t *json) { + void parse(json_t *json) override { assert(state == State::INITIALIZED); state = State::PARSED; @@ -191,7 +191,7 @@ class HookFactory : public plugin::Plugin { virtual unsigned getPriority() const = 0; - virtual std::string getType() const { return "hook"; } + std::string getType() const override { return "hook"; } virtual bool isHidden() const { return false; } }; @@ -203,7 +203,7 @@ class HookPlugin : public HookFactory { public: using HookFactory::HookFactory; - virtual Hook::Ptr make(Path *p, Node *n) { + Hook::Ptr make(Path *p, Node *n) override { auto h = std::make_shared(p, n, getFlags(), getPriority()); init(h); @@ -211,13 +211,13 @@ class HookPlugin : public HookFactory { return h; } - virtual std::string getName() const { return name; } + std::string getName() const override { return name; } - virtual std::string getDescription() const { return desc; } + std::string getDescription() const override { return desc; } - virtual int getFlags() const { return flags; } + int getFlags() const override { return flags; } - virtual unsigned getPriority() const { return prio; } + unsigned getPriority() const override { return prio; } }; } // namespace node diff --git a/include/villas/hooks/lua.hpp b/include/villas/hooks/lua.hpp index f281b79cd..a9b5edd4d 100644 --- a/include/villas/hooks/lua.hpp +++ b/include/villas/hooks/lua.hpp @@ -21,7 +21,7 @@ namespace node { // Forward declarations class LuaHook; -enum SignalType; +enum class SignalType; class LuaSignalExpression { @@ -105,7 +105,7 @@ class LuaHook : public Hook { public: LuaHook(Path *p, Node *n, int fl, int prio, bool en = true); - virtual ~LuaHook(); + ~LuaHook() override; void parse(json_t *json) override; diff --git a/include/villas/node.hpp b/include/villas/node.hpp index f4c52a62e..ad8bb427e 100644 --- a/include/villas/node.hpp +++ b/include/villas/node.hpp @@ -219,7 +219,7 @@ class Node { // Just get the config details of this node as a string virtual const std::string &getDetails() { - static std::string empty; + static std::string const empty; return empty; } @@ -316,7 +316,7 @@ class NodeFactory : public villas::plugin::Plugin { static Node *make(const std::string &type, const uuid_t &id = {}, const std::string &name = ""); - virtual std::string getType() const { return "node"; } + std::string getType() const override { return "node"; } friend std::ostream &operator<<(std::ostream &os, const NodeFactory &f) { os << f.getName(); @@ -346,7 +346,7 @@ template T *getData() { return static_cast(_vd); } diff --git a/include/villas/nodes/comedi.hpp b/include/villas/nodes/comedi.hpp index 81881c5d8..38601bfc1 100644 --- a/include/villas/nodes/comedi.hpp +++ b/include/villas/nodes/comedi.hpp @@ -8,6 +8,7 @@ #pragma once #include +#include #include #include diff --git a/include/villas/nodes/example.hpp b/include/villas/nodes/example.hpp index c821bdde4..71c47f3a9 100644 --- a/include/villas/nodes/example.hpp +++ b/include/villas/nodes/example.hpp @@ -44,7 +44,7 @@ class ExampleNode : public Node { * Have a look at node.hpp/node.cpp for the default behaviour. */ - virtual ~ExampleNode(); + ~ExampleNode() override; int prepare() override; diff --git a/include/villas/nodes/exec.hpp b/include/villas/nodes/exec.hpp index 28e3d97c1..d1d014c61 100644 --- a/include/villas/nodes/exec.hpp +++ b/include/villas/nodes/exec.hpp @@ -42,7 +42,7 @@ class ExecNode : public Node { : Node(id, name), stream_in(nullptr), stream_out(nullptr), flush(true), shell(false) {} - virtual ~ExecNode(); + ~ExecNode() override; const std::string &getDetails() override; diff --git a/include/villas/nodes/fpga.hpp b/include/villas/nodes/fpga.hpp index 8264fa616..d70bd2995 100644 --- a/include/villas/nodes/fpga.hpp +++ b/include/villas/nodes/fpga.hpp @@ -9,8 +9,6 @@ #pragma once -#include - #include #include @@ -80,7 +78,7 @@ class FpgaNode : public Node { public: FpgaNode(const uuid_t &id = {}, const std::string &name = ""); - virtual ~FpgaNode(); + ~FpgaNode() override; int prepare() override; diff --git a/include/villas/nodes/iec60870.hpp b/include/villas/nodes/iec60870.hpp index 707503e17..bd0335efc 100644 --- a/include/villas/nodes/iec60870.hpp +++ b/include/villas/nodes/iec60870.hpp @@ -201,7 +201,7 @@ class SlaveNode : public Node { public: SlaveNode(const uuid_t &id = {}, const std::string &name = ""); - virtual ~SlaveNode() override; + ~SlaveNode() override; int parse(json_t *json) override; diff --git a/include/villas/nodes/iec61850_goose.hpp b/include/villas/nodes/iec61850_goose.hpp index efe56890a..6124ff178 100644 --- a/include/villas/nodes/iec61850_goose.hpp +++ b/include/villas/nodes/iec61850_goose.hpp @@ -240,7 +240,7 @@ class GooseNode : public Node { public: GooseNode(const uuid_t &id = {}, const std::string &name = ""); - virtual ~GooseNode() override; + ~GooseNode() override; std::vector getPollFDs() override; diff --git a/include/villas/nodes/loopback.hpp b/include/villas/nodes/loopback.hpp index 930e641de..da281d5e8 100644 --- a/include/villas/nodes/loopback.hpp +++ b/include/villas/nodes/loopback.hpp @@ -28,7 +28,7 @@ class LoopbackNode : public Node { public: LoopbackNode(const uuid_t &id = {}, const std::string &name = ""); - virtual ~LoopbackNode(); + ~LoopbackNode() override; int prepare() override; diff --git a/include/villas/nodes/loopback_internal.hpp b/include/villas/nodes/loopback_internal.hpp index 411268ba0..b5f130985 100644 --- a/include/villas/nodes/loopback_internal.hpp +++ b/include/villas/nodes/loopback_internal.hpp @@ -28,7 +28,7 @@ class InternalLoopbackNode : public Node { InternalLoopbackNode(Node *src, unsigned id = 0, unsigned ql = DEFAULT_QUEUE_LENGTH); - virtual ~InternalLoopbackNode(); + ~InternalLoopbackNode() override; std::vector getPollFDs() override; diff --git a/include/villas/nodes/modbus.hpp b/include/villas/nodes/modbus.hpp index d6c455cd6..ce67df311 100644 --- a/include/villas/nodes/modbus.hpp +++ b/include/villas/nodes/modbus.hpp @@ -275,7 +275,7 @@ class ModbusNode final : public Node { public: ModbusNode(const uuid_t &id = {}, const std::string &name = ""); - virtual ~ModbusNode(); + ~ModbusNode() override; int prepare() override; diff --git a/include/villas/nodes/mqtt.hpp b/include/villas/nodes/mqtt.hpp index 53c9ea750..08aa32ac2 100644 --- a/include/villas/nodes/mqtt.hpp +++ b/include/villas/nodes/mqtt.hpp @@ -7,6 +7,8 @@ #pragma once +#include + #include #include #include diff --git a/include/villas/nodes/ngsi.hpp b/include/villas/nodes/ngsi.hpp index 8604343a7..bbc708edf 100644 --- a/include/villas/nodes/ngsi.hpp +++ b/include/villas/nodes/ngsi.hpp @@ -17,6 +17,7 @@ #include #include +#include #include namespace villas { diff --git a/include/villas/nodes/opendss.hpp b/include/villas/nodes/opendss.hpp index 1f6e85b65..bc6acb4b1 100644 --- a/include/villas/nodes/opendss.hpp +++ b/include/villas/nodes/opendss.hpp @@ -59,7 +59,7 @@ class OpenDSS : public Node { public: OpenDSS(const uuid_t &id = {}, const std::string &name = ""); - virtual ~OpenDSS(); + ~OpenDSS() override; int prepare() override; diff --git a/include/villas/nodes/temper.hpp b/include/villas/nodes/temper.hpp index 3eeeabcbf..ad0073c73 100644 --- a/include/villas/nodes/temper.hpp +++ b/include/villas/nodes/temper.hpp @@ -52,7 +52,7 @@ class TEMPerDevice : public villas::usb::Device { class TEMPer1Device : public TEMPerDevice { protected: - virtual void decode(unsigned char *answer, float *temp); + void decode(unsigned char *answer, float *temp) override; using TEMPerDevice::TEMPerDevice; @@ -65,7 +65,7 @@ class TEMPer1Device : public TEMPerDevice { class TEMPer2Device : public TEMPer1Device { protected: - virtual void decode(unsigned char *answer, float *temp); + void decode(unsigned char *answer, float *temp) override; using TEMPer1Device::TEMPer1Device; @@ -74,13 +74,13 @@ class TEMPer2Device : public TEMPer1Device { static std::string getName() { return "TEMPer2"; } - virtual int getNumSensors() const { return 2; } + int getNumSensors() const override { return 2; } }; class TEMPerHUMDevice : public TEMPerDevice { protected: - virtual void decode(unsigned char *answer, float *temp); + void decode(unsigned char *answer, float *temp) override; using TEMPerDevice::TEMPerDevice; @@ -89,7 +89,7 @@ class TEMPerHUMDevice : public TEMPerDevice { static std::string getName() { return "TEMPerHUM"; } - virtual bool hasHumiditySensor() const { return true; } + bool hasHumiditySensor() const override { return true; } }; struct temper { diff --git a/include/villas/nodes/test_rtt.hpp b/include/villas/nodes/test_rtt.hpp index abf26db2e..4602785c3 100644 --- a/include/villas/nodes/test_rtt.hpp +++ b/include/villas/nodes/test_rtt.hpp @@ -95,7 +95,7 @@ class TestRTT : public Node { : Node(id, name), task(), formatter(nullptr), stream(nullptr), shutdown(false) {} - virtual ~TestRTT(){}; + ~TestRTT() override{}; int prepare() override; diff --git a/include/villas/nodes/webrtc.hpp b/include/villas/nodes/webrtc.hpp index f09e524c6..a562bd683 100644 --- a/include/villas/nodes/webrtc.hpp +++ b/include/villas/nodes/webrtc.hpp @@ -50,7 +50,7 @@ class WebRTCNode : public Node { public: WebRTCNode(const uuid_t &id = {}, const std::string &name = ""); - virtual ~WebRTCNode(); + ~WebRTCNode() override; int prepare() override; diff --git a/include/villas/path_source.hpp b/include/villas/path_source.hpp index 5967e0902..ce5870ca6 100644 --- a/include/villas/path_source.hpp +++ b/include/villas/path_source.hpp @@ -81,7 +81,7 @@ class MasterPathSource : public PathSource { const SecondaryPathSourceList &getSecondaries() { return secondaries; } - virtual void writeToSecondaries(struct Sample *smps[], unsigned cnt); + void writeToSecondaries(struct Sample *smps[], unsigned cnt) override; }; } // namespace node diff --git a/include/villas/queue.hpp b/include/villas/queue.hpp index 236bd62d4..852aa6fed 100644 --- a/include/villas/queue.hpp +++ b/include/villas/queue.hpp @@ -20,13 +20,13 @@ template class Queue { public: void push(T p) { - std::unique_lock guard(mtx); + std::unique_lock const guard(mtx); queue.push(p); } T pop() { - std::unique_lock guard(mtx); + std::unique_lock const guard(mtx); T res = queue.front(); queue.pop(); @@ -35,7 +35,7 @@ template class Queue { } bool empty() { - std::unique_lock guard(mtx); + std::unique_lock const guard(mtx); return queue.empty(); } diff --git a/include/villas/signal_list.hpp b/include/villas/signal_list.hpp index 9a326abfd..a3d445e06 100644 --- a/include/villas/signal_list.hpp +++ b/include/villas/signal_list.hpp @@ -29,7 +29,7 @@ class SignalList : public std::vector { SignalList(unsigned len, enum SignalType fmt); SignalList(const char *dt); SignalList(json_t *json) { - int ret = parse(json); + int const ret = parse(json); if (ret) throw RuntimeError("Failed to parse signal list"); } diff --git a/include/villas/usb.hpp b/include/villas/usb.hpp index e77da36f8..e4060384d 100644 --- a/include/villas/usb.hpp +++ b/include/villas/usb.hpp @@ -47,12 +47,12 @@ class Error : public std::runtime_error { Error(int e, const std::string &what, Args &&...args) : usb::Error((enum libusb_error)e, what, std::forward(args)...) {} - ~Error() { + ~Error() override { if (msg) free(msg); } - virtual const char *what() const noexcept { return msg; } + const char *what() const noexcept override { return msg; } }; class Device { diff --git a/lib/api/requests/graph.cpp b/lib/api/requests/graph.cpp index 2d5ed0d6e..a4410d295 100644 --- a/lib/api/requests/graph.cpp +++ b/lib/api/requests/graph.cpp @@ -32,7 +32,7 @@ class GraphRequest : public Request { layout = "neato"; } - ~GraphRequest() { gvFreeContext(gvc); } + ~GraphRequest() override { gvFreeContext(gvc); } Response *execute() override { if (method != Session::Method::GET) diff --git a/lib/api/requests/node_action.cpp b/lib/api/requests/node_action.cpp index df66a9ff2..5fa6d04ad 100644 --- a/lib/api/requests/node_action.cpp +++ b/lib/api/requests/node_action.cpp @@ -31,7 +31,7 @@ template class NodeActionRequest : public NodeRequest { if (body != nullptr) throw BadRequest("Node endpoints do not accept any body data"); - int ret = (node->*func)(); + int const ret = (node->*func)(); if (ret) throw BadRequest("Failed to execute action", "{ s: d }", "ret", ret); diff --git a/lib/api/requests/node_file.cpp b/lib/api/requests/node_file.cpp index 436cd84d1..947e5fb7d 100644 --- a/lib/api/requests/node_file.cpp +++ b/lib/api/requests/node_file.cpp @@ -33,13 +33,15 @@ class FileRequest : public NodeRequest { if (node->getFactory() != nf) throw BadRequest("This node is not a file node", "{ s: s }", "type", - node->getFactory()->getName()); + node->getFactory()->getName().c_str()); auto *nc = dynamic_cast(node); auto *f = nc->getData(); - if (matches[2] == "rewind") + if (matches[2] == "rewind") { rewind(f->stream_in); + (void)errno; // TODO: Should we handle rewind errors? + } return new Response(session, HTTP_STATUS_OK); } diff --git a/lib/api/requests/restart.cpp b/lib/api/requests/restart.cpp index 968d42f2b..b2cd7b90a 100644 --- a/lib/api/requests/restart.cpp +++ b/lib/api/requests/restart.cpp @@ -28,7 +28,7 @@ class RestartRequest : public Request { const char *argv[] = {"villas-node", cfg, nullptr}; - Logger logger = Log::get("api:restart"); + Logger const logger = Log::get("api:restart"); if (cfg) logger->info("Restarting instance: config={}", cfg); @@ -63,14 +63,20 @@ class RestartRequest : public Request { configUri = json_string_value(json_config); else if (json_is_object(json_config)) { char configUriBuf[] = "villas-node.json.XXXXXX"; - int configFd = mkstemp(configUriBuf); + int const configFd = mkstemp(configUriBuf); + if (configFd < 0) + throw Error(HTTP_STATUS_INTERNAL_SERVER_ERROR, + "Failed to create temporary config file"); FILE *configFile = fdopen(configFd, "w+"); + if (configFile == nullptr) + throw Error(HTTP_STATUS_INTERNAL_SERVER_ERROR, + "Failed to open temporary config file"); ret = json_dumpf(json_config, configFile, JSON_INDENT(4)); if (ret < 0) throw Error(HTTP_STATUS_INTERNAL_SERVER_ERROR, - "Failed to create temporary config file"); + "Failed to write temporary config file"); fclose(configFile); configUri = configUriBuf; @@ -84,7 +90,7 @@ class RestartRequest : public Request { // Increment API restart counter char *scnt = getenv("VILLAS_API_RESTART_COUNT"); - int cnt = scnt ? atoi(scnt) : 0; + int const cnt = scnt ? atoi(scnt) : 0; char buf[32]; snprintf(buf, sizeof(buf), "%d", cnt + 1); diff --git a/lib/api/requests/status.cpp b/lib/api/requests/status.cpp index a97b5d5f2..a4cdb60cf 100644 --- a/lib/api/requests/status.cpp +++ b/lib/api/requests/status.cpp @@ -56,7 +56,7 @@ class StatusRequest : public Request { throw Error(HTTP_STATUS_INTERNAL_SERVER_ERROR, "Failed to get system information"); - float f_load = 1.f / (1 << SI_LOAD_SHIFT); + float const f_load = 1.f / (1 << SI_LOAD_SHIFT); tzset(); diff --git a/lib/api/requests/universal.cpp b/lib/api/requests/universal.cpp index d3083cef5..e64e42ae9 100644 --- a/lib/api/requests/universal.cpp +++ b/lib/api/requests/universal.cpp @@ -16,6 +16,6 @@ void UniversalRequest::prepare() { api_node = dynamic_cast(node); if (!api_node) - throw BadRequest("Node {} is not an univeral API node!", + throw BadRequest("Node {} is not an universal API node!", node->getNameShort()); } diff --git a/lib/config.cpp b/lib/config.cpp index 0bd9cc190..e86ee98c1 100644 --- a/lib/config.cpp +++ b/lib/config.cpp @@ -180,14 +180,15 @@ std::list Config::resolveIncludes(const std::string &n) { return files; } +// TODO: remove this this code void Config::resolveEnvVars(std::string &text) { static const std::regex env_re{R"--(\$\{([^}]+)\})--"}; std::smatch match; while (std::regex_search(text, match, env_re)) { auto const from = match[0]; - auto const var_name = match[1].str().c_str(); - char *var_value = std::getenv(var_name); + auto const var_name = match[1].str(); + char *var_value = std::getenv(var_name.c_str()); if (!var_value) throw RuntimeError("Unresolved environment variable: {}", var_name); @@ -215,7 +216,7 @@ const char **Config::includeFunc(config_t *cfg, const char *include_dir, auto paths = resolveIncludes(path); unsigned i = 0; - auto files = (const char **)malloc(sizeof(char **) * (paths.size() + 1)); + auto files = (const char **)malloc(sizeof(const char *) * (paths.size() + 1)); for (auto &path : paths) files[i++] = strdup(path.c_str()); @@ -257,6 +258,7 @@ json_t *Config::libconfigDecode(FILE *f) { // Rewind before re-reading rewind(f); + (void)errno; // TODO: should we handle rewind errors? ret = config_read(&cfg, f); if (ret != CONFIG_TRUE) @@ -323,7 +325,7 @@ json_t *Config::expandEnvVars(json_t *in) { json_t *Config::expandIncludes(json_t *in) { return walkStrings(in, [this](json_t *str) -> json_t * { int ret; - std::string text = json_string_value(str); + std::string const text = json_string_value(str); static const std::string kw = "@include "; if (text.find(kw) != 0) diff --git a/lib/config_helper.cpp b/lib/config_helper.cpp index cc36c5dab..46289b909 100644 --- a/lib/config_helper.cpp +++ b/lib/config_helper.cpp @@ -167,7 +167,7 @@ void villas::node::json_object_extend_key_value_token(json_t *obj, void villas::node::json_object_extend_key_value(json_t *obj, const char *key, const char *value) { - char *end, *cpy, *key1, *key2, *lasts; + char *end, *key1, *key2, *lasts; double real; long integer; @@ -176,9 +176,9 @@ void villas::node::json_object_extend_key_value(json_t *obj, const char *key, // Is the key pointing to an object? subobj = obj; - cpy = strdup(key); + auto cpy = std::string{key}; - key1 = strtok_r(cpy, ".", &lasts); + key1 = strtok_r(cpy.data(), ".", &lasts); key2 = strtok_r(nullptr, ".", &lasts); while (key1 && key2) { @@ -320,11 +320,11 @@ int villas::node::json_object_extend(json_t *obj, json_t *merge) { } int villas::node::json_object_extend_str(json_t *obj, const char *str) { - char *key, *value, *cpy, *lasts; + char *key, *value, *lasts; - cpy = strdup(str); + auto cpy = std::string{str}; - key = strtok_r(cpy, "=", &lasts); + key = strtok_r(cpy.data(), "=", &lasts); value = strtok_r(nullptr, "", &lasts); if (!key || !value) @@ -332,7 +332,5 @@ int villas::node::json_object_extend_str(json_t *obj, const char *str) { json_object_extend_key_value_token(obj, key, value); - free(cpy); - return 0; } diff --git a/lib/dumper.cpp b/lib/dumper.cpp index 4bc56664b..9374fc513 100644 --- a/lib/dumper.cpp +++ b/lib/dumper.cpp @@ -40,9 +40,10 @@ int Dumper::openSocket() { sockaddr_un socketaddrUn; socketaddrUn.sun_family = AF_UNIX; - strcpy(socketaddrUn.sun_path, socketPath.c_str()); + assert(socketPath.size() < sizeof(socketaddrUn.sun_path)); + memcpy(socketaddrUn.sun_path, socketPath.c_str(), socketPath.size() + 1); - int ret = + int const ret = connect(socketFd, (struct sockaddr *)&socketaddrUn, sizeof(socketaddrUn)); if (!ret) return ret; @@ -51,7 +52,7 @@ int Dumper::openSocket() { } int Dumper::closeSocket() { - int ret = close(socketFd); + int const ret = close(socketFd); if (!ret) return ret; diff --git a/lib/formats/json.cpp b/lib/formats/json.cpp index 795c0c129..444d71bc5 100644 --- a/lib/formats/json.cpp +++ b/lib/formats/json.cpp @@ -15,7 +15,7 @@ using namespace villas; using namespace villas::node; enum SignalType JsonFormat::detect(const json_t *val) { - int type = json_typeof(val); + int const type = json_typeof(val); switch (type) { case JSON_REAL: @@ -247,7 +247,7 @@ int JsonFormat::unpackSample(json_t *json_smp, struct Sample *smp) { if (!sig) return -1; - enum SignalType fmt = detect(json_value); + enum SignalType const fmt = detect(json_value); if (sig->type != fmt) throw RuntimeError("Received invalid data type in JSON payload: Received " "{}, expected {} for signal {} (index {}).", diff --git a/lib/formats/json_kafka.cpp b/lib/formats/json_kafka.cpp index 32f1c6e25..3c3999f08 100644 --- a/lib/formats/json_kafka.cpp +++ b/lib/formats/json_kafka.cpp @@ -42,7 +42,7 @@ int JsonKafkaFormat::packSample(json_t **json_smp, const struct Sample *smp) { json_field = json_pack("{ s: s, s: b, s: s }", "type", "int64", "optional", false, "field", "timestamp"); - uint64_t ts_origin_ms = + uint64_t const ts_origin_ms = smp->ts.origin.tv_sec * 1e3 + smp->ts.origin.tv_nsec / 1e6; json_array_append_new(json_fields, json_field); json_object_set_new(json_payload, "timestamp", json_integer(ts_origin_ms)); @@ -64,7 +64,7 @@ int JsonKafkaFormat::packSample(json_t **json_smp, const struct Sample *smp) { json_field = json_pack("{ s: s, s: b, s: s }", "type", villasToKafkaType(sig->type), - "optional", false, "field", sig->name); + "optional", false, "field", sig->name.c_str()); json_value = data->toJson(sig->type); @@ -97,7 +97,7 @@ int JsonKafkaFormat::unpackSample(json_t *json_smp, struct Sample *smp) { // Unpack timestamp json_value = json_object_get(json_payload, "timestamp"); if (json_value) { - uint64_t ts_origin_ms = json_integer_value(json_value); + uint64_t const ts_origin_ms = json_integer_value(json_value); smp->ts.origin = time_from_double(ts_origin_ms / 1e3); smp->flags |= (int)SampleFlags::HAS_TS_ORIGIN; diff --git a/lib/formats/msg.cpp b/lib/formats/msg.cpp index 31818b8f2..6bbf8a814 100644 --- a/lib/formats/msg.cpp +++ b/lib/formats/msg.cpp @@ -66,7 +66,7 @@ int villas::node::msg_to_sample(const struct Message *msg, struct Sample *smp, if (ret) return ret; - unsigned len = MIN(msg->length, smp->capacity); + unsigned const len = MIN(msg->length, smp->capacity); for (i = 0; i < MIN(len, sigs->size()); i++) { auto sig = sigs->getByIndex(i); if (!sig) diff --git a/lib/formats/opal_asyncip.cpp b/lib/formats/opal_asyncip.cpp index eb438329e..91ef5461e 100644 --- a/lib/formats/opal_asyncip.cpp +++ b/lib/formats/opal_asyncip.cpp @@ -19,7 +19,7 @@ int OpalAsyncIPFormat::sprint(char *buf, size_t len, size_t *wbytes, const struct Sample *const smps[], unsigned cnt) { unsigned i; auto *ptr = buf; - ssize_t slen = len; + ssize_t const slen = len; for (i = 0; i < cnt && ptr - buf < slen; i++) { auto *pl = (struct Payload *)ptr; diff --git a/lib/formats/protobuf.cpp b/lib/formats/protobuf.cpp index c34913bcc..f97ee34e6 100644 --- a/lib/formats/protobuf.cpp +++ b/lib/formats/protobuf.cpp @@ -96,7 +96,7 @@ int ProtobufFormat::sprint(char *buf, size_t len, size_t *wbytes, villas__node__value__init(pb_val); - enum SignalType fmt = sample_format(smp, j); + enum SignalType const fmt = sample_format(smp, j); switch (fmt) { case SignalType::FLOAT: pb_val->value_case = VILLAS__NODE__VALUE__VALUE_F; @@ -187,7 +187,7 @@ int ProtobufFormat::sscan(const char *buf, size_t len, size_t *rbytes, for (j = 0; j < MIN(pb_smp->n_values, smp->capacity); j++) { Villas__Node__Value *pb_val = pb_smp->values[j]; - enum SignalType fmt = detect(pb_val); + enum SignalType const fmt = detect(pb_val); auto sig = smp->signals->getByIndex(j); if (!sig) diff --git a/lib/formats/raw.cpp b/lib/formats/raw.cpp index ea82c2960..777753209 100644 --- a/lib/formats/raw.cpp +++ b/lib/formats/raw.cpp @@ -125,7 +125,7 @@ int RawFormat::sprint(char *buf, size_t len, size_t *wbytes, } for (unsigned j = 0; j < smp->length; j++) { - enum SignalType fmt = sample_format(smp, j); + enum SignalType const fmt = sample_format(smp, j); const union SignalData *data = &smp->data[j]; // Check length @@ -287,7 +287,7 @@ int RawFormat::sscan(const char *buf, size_t len, size_t *rbytes, struct Sample *smp = smps[0]; int o = 0; - int nlen = len / (bits / 8); + int const nlen = len / (bits / 8); if (cnt > 1) return -1; @@ -355,7 +355,7 @@ int RawFormat::sscan(const char *buf, size_t len, size_t *rbytes, unsigned i; for (i = 0; i < smp->capacity && o < nlen; i++) { - enum SignalType fmt = sample_format(smp, i); + enum SignalType const fmt = sample_format(smp, i); union SignalData *data = &smp->data[i]; switch (fmt) { diff --git a/lib/formats/villas_human.cpp b/lib/formats/villas_human.cpp index 6353e7488..bafc29ce5 100644 --- a/lib/formats/villas_human.cpp +++ b/lib/formats/villas_human.cpp @@ -153,7 +153,7 @@ size_t VILLASHumanFormat::sscanLine(const char *buf, size_t len, smp->flags |= (int)SampleFlags::HAS_DATA; if (smp->flags & (int)SampleFlags::HAS_OFFSET) { - struct timespec off = time_from_double(offset); + struct timespec const off = time_from_double(offset); smp->ts.received = time_add(&smp->ts.origin, &off); smp->flags |= (int)SampleFlags::HAS_TS_RECEIVED; diff --git a/lib/hook.cpp b/lib/hook.cpp index feb61efa2..32379450a 100644 --- a/lib/hook.cpp +++ b/lib/hook.cpp @@ -87,7 +87,7 @@ void SingleSignalHook::prepare() { Hook::prepare(); // Setup mask - int index = signals->getIndexByName(signalName.c_str()); + int const index = signals->getIndexByName(signalName.c_str()); if (index < 0) throw RuntimeError("Failed to find signal {}", signalName); diff --git a/lib/hook_list.cpp b/lib/hook_list.cpp index c0f31bb1c..21a63d4f4 100644 --- a/lib/hook_list.cpp +++ b/lib/hook_list.cpp @@ -167,7 +167,7 @@ unsigned HookList::getSignalsMaxCount() const { unsigned max_cnt = 0; for (auto h : *this) { - unsigned sigs_cnt = h->getSignals()->size(); + unsigned const sigs_cnt = h->getSignals()->size(); if (sigs_cnt > max_cnt) max_cnt = sigs_cnt; diff --git a/lib/hooks/average.cpp b/lib/hooks/average.cpp index 3b428ab51..05d805966 100644 --- a/lib/hooks/average.cpp +++ b/lib/hooks/average.cpp @@ -58,7 +58,7 @@ class AverageHook : public MultiSignalHook { assert(state == State::STARTED); - for (unsigned index : signalIndices) { + for (unsigned const index : signalIndices) { switch (sample_format(smp, index)) { case SignalType::INTEGER: sum += smp->data[index].i; diff --git a/lib/hooks/digest.cpp b/lib/hooks/digest.cpp index 0d82cfc35..64bda78d2 100644 --- a/lib/hooks/digest.cpp +++ b/lib/hooks/digest.cpp @@ -197,7 +197,7 @@ class DigestHook : public Hook { char const *algorithm_str; json_error_t err; - int ret = + int const ret = json_unpack_ex(json, &err, 0, "{ s: s, s?: s, s?: s }", "uri", &uri_str, "mode", &mode_str, "algorithm", &algorithm_str); if (ret) @@ -221,7 +221,7 @@ class DigestHook : public Hook { throw RuntimeError{"Could not fetch algorithm {}", algorithm}; } - virtual void start() override { + void start() override { Hook::start(); if (!EVP_DigestInit_ex(md_ctx.get(), md, NULL)) @@ -238,7 +238,7 @@ class DigestHook : public Hook { return Reason::OK; } - virtual void stop() override { + void stop() override { Hook::stop(); first_sequence.reset(); diff --git a/lib/hooks/dp.cpp b/lib/hooks/dp.cpp index ebce15a66..c76e7ee30 100644 --- a/lib/hooks/dp.cpp +++ b/lib/hooks/dp.cpp @@ -40,10 +40,10 @@ class DPHook : public Hook { dsp::Window window; void step(double *in, std::complex *out) { - int N = window.size(); + int const N = window.size(); std::complex om_k, corr; - double newest = *in; - __attribute__((unused)) double oldest = window.update(newest); + double const newest = *in; + __attribute__((unused)) double const oldest = window.update(newest); for (int k = 0; k < fharmonics_len; k++) { om_k = 2.0i * M_PI * (double)fharmonics[k] / (double)N; @@ -66,7 +66,7 @@ class DPHook : public Hook { std::complex X_k = 0; for (int n = 0; n < N; n++) { - double x_n = window[n]; + double const x_n = window[n]; X_k += x_n * std::exp(om_k * (double)n); } @@ -81,10 +81,10 @@ class DPHook : public Hook { // Reconstruct the original signal for (int k = 0; k < fharmonics_len; k++) { - double freq = fharmonics[k]; + double const freq = fharmonics[k]; // cppcheck-suppress objectIndex - std::complex coeff = in[k]; - std::complex om = 2.0i * M_PI * freq * time; + std::complex const coeff = in[k]; + std::complex const om = 2.0i * M_PI * freq * time; value += coeff * std::exp(om); } @@ -98,7 +98,7 @@ class DPHook : public Hook { inverse(0), f0(50.0), timestep(50e-6), time(), steps(0), coeffs(), fharmonics(), fharmonics_len(0) {} - virtual ~DPHook() { + ~DPHook() override { // Release memory if (fharmonics) delete fharmonics; @@ -110,7 +110,7 @@ class DPHook : public Hook { free(signal_name); } - virtual void start() override { + void start() override { assert(state == State::PREPARED); time = 0; @@ -198,7 +198,7 @@ class DPHook : public Hook { assert(state != State::STARTED); if (signal_name) { - int si = signals->getIndexByName(signal_name); + int const si = signals->getIndexByName(signal_name); if (si < 0) { throw RuntimeError("Failed to find signal: {}", signal_name); } @@ -249,7 +249,7 @@ class DPHook : public Hook { state = State::PREPARED; } - virtual void check() { + void check() override { assert(state == State::PARSED); if (signal_index < 0) diff --git a/lib/hooks/drop.cpp b/lib/hooks/drop.cpp index ac6a5728f..5e41e1c06 100644 --- a/lib/hooks/drop.cpp +++ b/lib/hooks/drop.cpp @@ -19,7 +19,7 @@ class DropHook : public Hook { public: using Hook::Hook; - virtual void start() override { + void start() override { assert(state == State::PREPARED || state == State::STOPPED); prev = nullptr; @@ -27,7 +27,7 @@ class DropHook : public Hook { state = State::STARTED; } - virtual void stop() override { + void stop() override { assert(state == State::STARTED); if (prev) @@ -60,7 +60,7 @@ class DropHook : public Hook { return Reason::OK; } - virtual void restart() { + void restart() override { assert(state == State::STARTED); if (prev) { diff --git a/lib/hooks/ebm.cpp b/lib/hooks/ebm.cpp index e134f611d..a9289c9ae 100644 --- a/lib/hooks/ebm.cpp +++ b/lib/hooks/ebm.cpp @@ -55,7 +55,7 @@ class EBMHook : public Hook { state = State::PARSED; } - virtual void start() override { + void start() override { assert(state == State::PREPARED); energy = 0; @@ -64,7 +64,7 @@ class EBMHook : public Hook { state = State::STARTED; } - virtual void periodic() override { + void periodic() override { assert(state == State::STARTED); logger->info("Energy: {}", energy); diff --git a/lib/hooks/fix.cpp b/lib/hooks/fix.cpp index 4f4d4833e..781feaf77 100644 --- a/lib/hooks/fix.cpp +++ b/lib/hooks/fix.cpp @@ -21,7 +21,7 @@ class FixHook : public Hook { Hook::Reason process(struct Sample *smp) override { assert(state == State::STARTED); - timespec now = time_now(); + timespec const now = time_now(); if (!(smp->flags & (int)SampleFlags::HAS_SEQUENCE) && node) { smp->sequence = node->sequence++; diff --git a/lib/hooks/frame.cpp b/lib/hooks/frame.cpp index 531196d87..88de380d7 100644 --- a/lib/hooks/frame.cpp +++ b/lib/hooks/frame.cpp @@ -173,7 +173,7 @@ class FrameHook : public Hook { : Hook(p, n, fl, prio, en), trigger(Trigger::SEQUENCE), interval(1), offset(0), unit{std::nullopt}, last_smp{nullptr, &sample_decref} {} - virtual ~FrameHook() { (void)last_smp.release(); } + ~FrameHook() override { (void)last_smp.release(); } void parse(json_t *json) override { Hook::parse(json); @@ -227,7 +227,7 @@ class FrameHook : public Hook { } } - virtual Hook::Reason process(Sample *smp) override { + Hook::Reason process(Sample *smp) override { Hook::process(smp); if (updateInterval(smp)) @@ -241,7 +241,7 @@ class FrameHook : public Hook { return Reason::OK; } - virtual void stop() override { + void stop() override { Hook::stop(); last_smp = nullptr; diff --git a/lib/hooks/gate.cpp b/lib/hooks/gate.cpp index 265eac9ab..1c1f31b8c 100644 --- a/lib/hooks/gate.cpp +++ b/lib/hooks/gate.cpp @@ -86,7 +86,7 @@ class GateHook : public SingleSignalHook { assert(state == State::STARTED); Hook::Reason reason; - double value = smp->data[signalIndex].f; + double const value = smp->data[signalIndex].f; if (active) { if (duration > 0 && time_delta(&smp->ts.origin, &startTime) < duration) diff --git a/lib/hooks/jitter_calc.cpp b/lib/hooks/jitter_calc.cpp index d8af9074e..87edf840d 100644 --- a/lib/hooks/jitter_calc.cpp +++ b/lib/hooks/jitter_calc.cpp @@ -46,7 +46,7 @@ class JitterCalcHook : public Hook { Hook::Reason process(struct Sample *smp) override { assert(state == State::STARTED); - timespec now = time_now(); + timespec const now = time_now(); int64_t delay_sec, delay_nsec, curr_delay_us; delay_sec = now.tv_sec - smp->ts.origin.tv_sec; diff --git a/lib/hooks/lua.cpp b/lib/hooks/lua.cpp index 97f15368e..8adfb9d4d 100644 --- a/lib/hooks/lua.cpp +++ b/lib/hooks/lua.cpp @@ -36,7 +36,7 @@ class LuaError : public RuntimeError { public: LuaError(lua_State *l, int e) : RuntimeError(""), L(l), err(e) {} - virtual const char *what() const noexcept { + const char *what() const noexcept override { const char *msg; switch (err) { case LUA_ERRSYNTAX: @@ -285,74 +285,6 @@ static void lua_pushjson(lua_State *L, json_t *json) { } } -static json_t *lua_tojson(lua_State *L, int index = -1) { - double n; - const char *s; - bool b; - - switch (lua_type(L, index)) { - case LUA_TFUNCTION: - case LUA_TUSERDATA: - case LUA_TTHREAD: - case LUA_TLIGHTUSERDATA: - case LUA_TNIL: - return json_null(); - - case LUA_TNUMBER: - n = lua_tonumber(L, index); - return n == (int)n ? json_integer(n) : json_real(n); - - case LUA_TBOOLEAN: - b = lua_toboolean(L, index); - return json_boolean(b); - - case LUA_TSTRING: - s = lua_tostring(L, index); - return json_string(s); - - case LUA_TTABLE: { - int keys_total = 0, keys_int = 0, key_highest = -1; - - lua_pushnil(L); - while (lua_next(L, index) != 0) { - keys_total++; - if (lua_type(L, -2) == LUA_TNUMBER) { - int key = lua_tonumber(L, -1); - - if (key == (int)key) { - keys_int++; - if (key > key_highest) - key_highest = key; - } - } - lua_pop(L, 1); - } - - bool is_array = keys_total == keys_int && key_highest / keys_int > 0.5; - - json_t *json = is_array ? json_array() : json_object(); - - lua_pushnil(L); - while (lua_next(L, index) != 0) { - json_t *val = lua_tojson(L, -1); - if (is_array) { - int key = lua_tonumber(L, -2); - json_array_set(json, key, val); - } else { - const char *key = lua_tostring(L, -2); - if (key) // Skip table entries whose keys are neither string or number! - json_object_set(json, key, val); - } - lua_pop(L, 1); - } - - return json; - } - } - - return nullptr; -} - namespace villas { namespace node { @@ -382,7 +314,7 @@ void LuaSignalExpression::parseExpression(const std::string &expr) { auto fexpr = fmt::format("return {}", expr); - int err = luaL_loadstring(L, fexpr.c_str()); + int const err = luaL_loadstring(L, fexpr.c_str()); if (err) throw ConfigError(cfg, "node-config-hook-lua-signals", "Failed to load Lua expression: {}", lua_tostring(L, -1)); @@ -464,7 +396,7 @@ void LuaHook::parse(json_t *json) { void LuaHook::lookupFunctions() { int ret; - std::map funcs = { + std::map const funcs = { {"start", &functions.start}, {"stop", &functions.stop}, {"restart", &functions.restart}, {"prepare", &functions.prepare}, {"periodic", &functions.periodic}, {"process", &functions.process}}; @@ -579,7 +511,7 @@ void LuaHook::prepare() { logger->debug("Executing Lua function: prepare()"); lua_pushvalue(L, functions.prepare); lua_pushjson(L, config); - int ret = lua_pcall(L, 1, 0, 0); + int const ret = lua_pcall(L, 1, 0, 0); if (ret) throw LuaError(L, ret); } @@ -594,7 +526,7 @@ void LuaHook::start() { if (functions.start) { logger->debug("Executing Lua function: start()"); lua_pushvalue(L, functions.start); - int ret = lua_pcall(L, 0, 0, 0); + int const ret = lua_pcall(L, 0, 0, 0); if (ret) throw LuaError(L, ret); } @@ -611,7 +543,7 @@ void LuaHook::stop() { if (functions.stop) { logger->debug("Executing Lua function: stop()"); lua_pushvalue(L, functions.stop); - int ret = lua_pcall(L, 0, 0, 0); + int const ret = lua_pcall(L, 0, 0, 0); if (ret) throw LuaError(L, ret); } @@ -628,7 +560,7 @@ void LuaHook::restart() { if (functions.restart) { logger->debug("Executing Lua function: restart()"); lua_pushvalue(L, functions.restart); - int ret = lua_pcall(L, 0, 0, 0); + int const ret = lua_pcall(L, 0, 0, 0); if (ret) throw LuaError(L, ret); } else @@ -644,7 +576,7 @@ void LuaHook::periodic() { logger->debug("Executing Lua function: restart()"); lua_pushvalue(L, functions.periodic); - int ret = lua_pcall(L, 0, 0, 0); + int const ret = lua_pcall(L, 0, 0, 0); if (ret) throw LuaError(L, ret); } @@ -667,7 +599,7 @@ Hook::Reason LuaHook::process(struct Sample *smp) { lua_pushvalue(L, functions.process); lua_pushvalue(L, -2); // Push a copy since lua_pcall() will pop it - int ret = lua_pcall(L, 1, 1, 0); + int const ret = lua_pcall(L, 1, 1, 0); if (ret) throw LuaError(L, ret); diff --git a/lib/hooks/ma.cpp b/lib/hooks/ma.cpp index fee09b7fc..787582433 100644 --- a/lib/hooks/ma.cpp +++ b/lib/hooks/ma.cpp @@ -68,13 +68,14 @@ class MovingAverageHook : public MultiSignalHook { unsigned i = 0; for (auto index : signalIndices) { // The new value - double newValue = smp->data[index].f; + double const newValue = smp->data[index].f; // Append the new value to the history memory smpMemory[i][smpMemoryPosition % windowSize] = newValue; // Get the old value from the history - double oldValue = smpMemory[i][(smpMemoryPosition + 1) % windowSize]; + double const oldValue = + smpMemory[i][(smpMemoryPosition + 1) % windowSize]; // Update the accumulator accumulator += newValue; diff --git a/lib/hooks/pmu.cpp b/lib/hooks/pmu.cpp index 66b0c8a0b..73fe4e5cf 100644 --- a/lib/hooks/pmu.cpp +++ b/lib/hooks/pmu.cpp @@ -177,8 +177,8 @@ Hook::Reason PmuHook::process(struct Sample *smp) { if (!init && initSampleCount > windowSize) init = true; - timespec timeDiff = time_diff(&nextRun, &smp->ts.origin); - double tmpTimeDiff = time_to_double(&timeDiff); + timespec const timeDiff = time_diff(&nextRun, &smp->ts.origin); + double const tmpTimeDiff = time_to_double(&timeDiff); bool run = false; if (tmpTimeDiff > 0. && init) run = true; @@ -193,8 +193,9 @@ Hook::Reason PmuHook::process(struct Sample *smp) { } // Align time tag - double currentTimeTag = time_to_double(&smp->ts.origin); - double alignedTime = currentTimeTag - fmod(currentTimeTag, 1 / phasorRate); + double const currentTimeTag = time_to_double(&smp->ts.origin); + double const alignedTime = + currentTimeTag - fmod(currentTimeTag, 1 / phasorRate); nextRun = time_from_double(alignedTime + 1 / phasorRate); size_t tsPos = 0; diff --git a/lib/hooks/pmu_dft.cpp b/lib/hooks/pmu_dft.cpp index 7ab6de59a..3967bd53e 100644 --- a/lib/hooks/pmu_dft.cpp +++ b/lib/hooks/pmu_dft.cpp @@ -324,7 +324,7 @@ class PmuDftHook : public MultiSignalHook { state = State::PARSED; } - virtual void check() { + void check() override { assert(state == State::PARSED); if (endFreqency < 0 || endFreqency > sampleRate) @@ -355,7 +355,7 @@ class PmuDftHook : public MultiSignalHook { #endif bool run = false; - double smpNsec = smp->ts.origin.tv_sec * 1e9 + smp->ts.origin.tv_nsec; + double const smpNsec = smp->ts.origin.tv_sec * 1e9 + smp->ts.origin.tv_nsec; if (smpNsec > nextCalc) { run = true; @@ -394,7 +394,7 @@ class PmuDftHook : public MultiSignalHook { } } - int multiplier = + int const multiplier = paddingType == PaddingType::ZERO ? 1 : windowMultiplier; DftEstimate dftEstimate = {0}; @@ -408,9 +408,9 @@ class PmuDftHook : public MultiSignalHook { maxPos, startFrequency, frequencyResolution, multiplier, windowSize, windowCorrectionFactor); } else { - Point a = {absFrequencies[maxPos - 1], results[i][maxPos - 1]}; - Point b = {absFrequencies[maxPos + 0], results[i][maxPos + 0]}; - Point c = {absFrequencies[maxPos + 1], results[i][maxPos + 1]}; + Point const a = {absFrequencies[maxPos - 1], results[i][maxPos - 1]}; + Point const b = {absFrequencies[maxPos + 0], results[i][maxPos + 0]}; + Point const c = {absFrequencies[maxPos + 1], results[i][maxPos + 1]}; if (estType == EstimationType::QUADRATIC) dftEstimate = quadraticEstimation( @@ -499,7 +499,7 @@ class PmuDftHook : public MultiSignalHook { using namespace std::complex_literals; omega = exp((-2i * M_PI) / (double)(windowSize * windowMultiplier)); - unsigned startBin = floor(startFrequency / frequencyResolution); + unsigned const startBin = floor(startFrequency / frequencyResolution); for (unsigned i = 0; i < freqCount; i++) { for (unsigned j = 0; j < windowSize * windowMultiplier; j++) @@ -588,14 +588,14 @@ class PmuDftHook : public MultiSignalHook { double frequencyResolution, double multiplier, double windowSize, double windowCorrectionFactor) { // Frequency estimation - double f_est = startFrequency + maxFBin * frequencyResolution; + double const f_est = startFrequency + maxFBin * frequencyResolution; // Amplitude estimation - double a_est = + double const a_est = abs(b.y) * 2 / (windowSize * windowCorrectionFactor * multiplier); //Phase estimation - double phase_est = atan2(b.y.imag(), b.y.real()); + double const phase_est = atan2(b.y.imag(), b.y.real()); return {a_est, f_est, phase_est}; } @@ -621,7 +621,7 @@ class PmuDftHook : public MultiSignalHook { } // Frequency estimation (eq 4) - double f_est = + double const f_est = startFrequency + ((double)maxFBin + delta) * frequencyResolution; // Amplitude estimation (eq 9) @@ -630,7 +630,7 @@ class PmuDftHook : public MultiSignalHook { a_est *= 2 / (windowSize * windowCorrectionFactor * multiplier); //Phase estimation (eq 10) - double phase_est = atan2(b.y.imag(), b.y.real()) - M_PI * delta; + double const phase_est = atan2(b.y.imag(), b.y.real()) - M_PI * delta; return {a_est, f_est, phase_est}; } @@ -650,35 +650,37 @@ class PmuDftHook : public MultiSignalHook { double windowCorrectionFactor) { using namespace std::complex_literals; - double ay_abs = + double const ay_abs = abs(a.y) * 2 / (windowSize * windowCorrectionFactor * multiplier); - double by_abs = + double const by_abs = abs(b.y) * 2 / (windowSize * windowCorrectionFactor * multiplier); - double cy_abs = + double const cy_abs = abs(c.y) * 2 / (windowSize * windowCorrectionFactor * multiplier); // Frequency estimation - double maxBinEst = (double)maxFBin + - (cy_abs - ay_abs) / (2 * (2 * by_abs - ay_abs - cy_abs)); - double f_est = startFrequency + - maxBinEst * frequencyResolution; // convert bin to frequency + double const maxBinEst = + (double)maxFBin + + (cy_abs - ay_abs) / (2 * (2 * by_abs - ay_abs - cy_abs)); + double const f_est = + startFrequency + + maxBinEst * frequencyResolution; // convert bin to frequency // Amplitude estimation - double f = (a.x * (by_abs - cy_abs) + b.x * (cy_abs - ay_abs) + - c.x * (ay_abs - by_abs)) / - ((a.x - b.x) * (a.x - c.x) * (c.x - b.x)); - double g = + double const f = (a.x * (by_abs - cy_abs) + b.x * (cy_abs - ay_abs) + + c.x * (ay_abs - by_abs)) / + ((a.x - b.x) * (a.x - c.x) * (c.x - b.x)); + double const g = (pow(a.x, 2) * (by_abs - cy_abs) + pow(b.x, 2) * (cy_abs - ay_abs) + pow(c.x, 2) * (ay_abs - by_abs)) / ((a.x - b.x) * (a.x - c.x) * (b.x - c.x)); - double h = (pow(a.x, 2) * (b.x * cy_abs - c.x * by_abs) + - a.x * (pow(c.x, 2) * by_abs - pow(b.x, 2) * cy_abs) + - b.x * c.x * ay_abs * (b.x - c.x)) / - ((a.x - b.x) * (a.x - c.x) * (b.x - c.x)); - double a_est = f * pow(f_est, 2) + g * f_est + h; + double const h = (pow(a.x, 2) * (b.x * cy_abs - c.x * by_abs) + + a.x * (pow(c.x, 2) * by_abs - pow(b.x, 2) * cy_abs) + + b.x * c.x * ay_abs * (b.x - c.x)) / + ((a.x - b.x) * (a.x - c.x) * (b.x - c.x)); + double const a_est = f * pow(f_est, 2) + g * f_est + h; //Phase estimation - double phase_est = atan2(b.y.imag(), b.y.real()); + double const phase_est = atan2(b.y.imag(), b.y.real()); return {a_est, f_est, phase_est}; } diff --git a/lib/hooks/pmu_ipdft.cpp b/lib/hooks/pmu_ipdft.cpp index 787cb76e5..af7806663 100644 --- a/lib/hooks/pmu_ipdft.cpp +++ b/lib/hooks/pmu_ipdft.cpp @@ -26,7 +26,7 @@ class IpDftPmuHook : public PmuHook { {} - void prepare() { + void prepare() override { PmuHook::prepare(); const double startFrequency = nominalFreq - estimationRange; @@ -44,7 +44,7 @@ class IpDftPmuHook : public PmuHook { using namespace std::complex_literals; omega = exp((-2i * M_PI) / (double)(windowSize)); - unsigned startBin = floor(startFrequency / frequencyResolution); + unsigned const startBin = floor(startFrequency / frequencyResolution); for (unsigned i = 0; i < frequencyCount; i++) { for (unsigned j = 0; j < windowSize; j++) @@ -53,7 +53,7 @@ class IpDftPmuHook : public PmuHook { } } - void parse(json_t *json) { + void parse(json_t *json) override { PmuHook::parse(json); int ret; @@ -110,10 +110,11 @@ class IpDftPmuHook : public PmuHook { const double startFrequency = nominalFreq - estimationRange; const double frequencyResolution = (double)sampleRate / windowSize; - double a = abs(dftResult[maxBin - 1]); - double b = abs(dftResult[maxBin + 0]); - double c = abs(dftResult[maxBin + 1]); - double bPhase = atan2(dftResult[maxBin].imag(), dftResult[maxBin].real()); + double const a = abs(dftResult[maxBin - 1]); + double const b = abs(dftResult[maxBin + 0]); + double const c = abs(dftResult[maxBin + 1]); + double const bPhase = + atan2(dftResult[maxBin].imag(), dftResult[maxBin].real()); // Estimate phasor // Based on https://ieeexplore.ieee.org/document/7980868 diff --git a/lib/hooks/power.cpp b/lib/hooks/power.cpp index 50e449a2b..fad3507e9 100644 --- a/lib/hooks/power.cpp +++ b/lib/hooks/power.cpp @@ -68,7 +68,7 @@ class PowerHook : public MultiSignalHook { MultiSignalHook::prepare(); for (unsigned i = 0; i < pairingsStr.size(); i++) { - PowerPairing p = { + PowerPairing const p = { .voltageIndex = signals->getIndexByName(pairingsStr[i].voltage), .currentIndex = signals->getIndexByName(pairingsStr[i].current)}; @@ -251,9 +251,9 @@ class PowerHook : public MultiSignalHook { auto pair = pairings[i]; // Update U integral - double oldValueU = + double const oldValueU = smpMemory[pair.voltageIndex][smpMemoryPosition % windowSize]; - double newValueU = smp->data[pair.voltageIndex].f; + double const newValueU = smp->data[pair.voltageIndex].f; smpMemory[pair.voltageIndex][smpMemoryPosition % windowSize] = newValueU; // Save for later @@ -261,8 +261,8 @@ class PowerHook : public MultiSignalHook { accumulator_u[i] += newValueU * newValueU; // Update I integral - double newValueI = smp->data[pair.currentIndex].f; - double oldValueI = + double const newValueI = smp->data[pair.currentIndex].f; + double const oldValueI = smpMemory[pair.currentIndex][smpMemoryPosition % windowSize]; smpMemory[pair.currentIndex][smpMemoryPosition % windowSize] = newValueI; // Save for later @@ -275,17 +275,17 @@ class PowerHook : public MultiSignalHook { accumulator_ui[i] += newValueI * newValueU; // Calc active power power - double P = (1.0 / windowSize) * accumulator_ui[i]; + double const P = (1.0 / windowSize) * accumulator_ui[i]; // Calc apparent power - double S = + double const S = (1.0 / windowSize) * pow(accumulator_i[i] * accumulator_u[i], 0.5); // Calc reactive power - double Q = pow(S * S - P * P, 0.5); + double const Q = pow(S * S - P * P, 0.5); // Calc cos phi - double PHI = atan2(Q, P) * angleUnitFactor; + double const PHI = atan2(Q, P) * angleUnitFactor; if (smpMemoryPosition >= windowSize) { // Write to samples diff --git a/lib/hooks/pps_ts.cpp b/lib/hooks/pps_ts.cpp index fe638760c..1c1c60930 100644 --- a/lib/hooks/pps_ts.cpp +++ b/lib/hooks/pps_ts.cpp @@ -86,7 +86,7 @@ class PpsTsHook : public SingleSignalHook { state = State::PARSED; } - virtual villas::node::Hook::Reason process(struct Sample *smp) { + villas::node::Hook::Reason process(struct Sample *smp) override { switch (mode) { case Mode::SIMPLE: return processSimple(smp); @@ -103,10 +103,11 @@ class PpsTsHook : public SingleSignalHook { assert(state == State::STARTED); // Get value of PPS signal - float value = smp->data[signalIndex].f; // TODO check if it is really float + float const value = + smp->data[signalIndex].f; // TODO check if it is really float // Detect Edge - bool isEdge = lastValue < threshold && value > threshold; + bool const isEdge = lastValue < threshold && value > threshold; if (isEdge) { tsVirt.tv_sec = currentSecond + 1; tsVirt.tv_nsec = 0; @@ -115,7 +116,7 @@ class PpsTsHook : public SingleSignalHook { cntEdges++; currentSecond = 0; } else { - struct timespec tsPeriod = time_from_double(period); + struct timespec const tsPeriod = time_from_double(period); tsVirt = time_add(&tsVirt, &tsPeriod); } @@ -145,10 +146,11 @@ class PpsTsHook : public SingleSignalHook { assert(state == State::STARTED); // Get value of PPS signal - float value = smp->data[signalIndex].f; // TODO check if it is really float + float const value = + smp->data[signalIndex].f; // TODO check if it is really float // Detect Edge - bool isEdge = lastValue < threshold && value > threshold; + bool const isEdge = lastValue < threshold && value > threshold; lastValue = value; @@ -161,9 +163,9 @@ class PpsTsHook : public SingleSignalHook { filterWindow[cntEdges % filterWindow.size()] = cntSmpsTotal; // Estimated sample period over last 'horizonEstimation' seconds - unsigned int tmp = + unsigned int const tmp = cntEdges < filterWindow.size() ? cntEdges : horizonEstimation; - double cntSmpsAvg = + double const cntSmpsAvg = (cntSmpsTotal - filterWindow[(cntEdges - tmp) % filterWindow.size()]) / tmp; @@ -195,7 +197,7 @@ class PpsTsHook : public SingleSignalHook { smp->ts.origin = tsVirt; smp->flags |= (int)SampleFlags::HAS_TS_ORIGIN; - struct timespec tsPeriod = time_from_double(period); + struct timespec const tsPeriod = time_from_double(period); tsVirt = time_add(&tsVirt, &tsPeriod); if ((smp->sequence - lastSequence) > 1) diff --git a/lib/hooks/print.cpp b/lib/hooks/print.cpp index 229970155..5b1eade8d 100644 --- a/lib/hooks/print.cpp +++ b/lib/hooks/print.cpp @@ -32,7 +32,7 @@ class PrintHook : public Hook { PrintHook(Path *p, Node *n, int fl, int prio, bool en = true) : Hook(p, n, fl, prio, en), output(nullptr) {} - virtual void start() override { + void start() override { assert(state == State::PREPARED || state == State::STOPPED); if (!output_path.empty()) { @@ -47,7 +47,7 @@ class PrintHook : public Hook { state = State::STARTED; } - virtual void stop() override { + void stop() override { if (output) fclose(output); } @@ -97,7 +97,7 @@ class PrintHook : public Hook { if (!output) { char *buf = output_buffer.data(); - size_t buflen = output_buffer.size(); + size_t const buflen = output_buffer.size(); size_t wbytes; formatter->sprint(buf, buflen, &wbytes, smp); diff --git a/lib/hooks/reorder_ts.cpp b/lib/hooks/reorder_ts.cpp index 7b96fb68e..01285b0f7 100644 --- a/lib/hooks/reorder_ts.cpp +++ b/lib/hooks/reorder_ts.cpp @@ -10,12 +10,11 @@ #include #include +#include #include #include #include -#include "villas/exceptions.hpp" - namespace villas { namespace node { @@ -49,7 +48,7 @@ class ReorderTsHook : public Hook { assert(state != State::STARTED); json_error_t err; - int ret = + int const ret = json_unpack_ex(json, &err, 0, "{ s?: i }", "window_size", &window_size); if (ret) throw ConfigError(json, err, "node-config-hook-reorder-ts"); @@ -57,7 +56,7 @@ class ReorderTsHook : public Hook { state = State::PARSED; } - virtual void start() override { + void start() override { assert(state == State::PREPARED || state == State::STOPPED); window.reserve(window_size); @@ -65,7 +64,7 @@ class ReorderTsHook : public Hook { state = State::STARTED; } - virtual void stop() override { + void stop() override { assert(state == State::STARTED); for (auto sample : window) @@ -79,7 +78,7 @@ class ReorderTsHook : public Hook { state = State::STOPPED; } - virtual Hook::Reason process(Sample *smp) { + Hook::Reason process(Sample *smp) override { assert(state == State::STARTED); assert(smp); @@ -134,7 +133,7 @@ class ReorderTsHook : public Hook { return Hook::Reason::SKIP_SAMPLE; } - virtual void restart() { + void restart() override { assert(state == State::STARTED); for (auto sample : window) diff --git a/lib/hooks/restart.cpp b/lib/hooks/restart.cpp index 116157715..37ea8018a 100644 --- a/lib/hooks/restart.cpp +++ b/lib/hooks/restart.cpp @@ -20,7 +20,7 @@ class RestartHook : public Hook { public: using Hook::Hook; - virtual void start() override { + void start() override { assert(state == State::PREPARED); prev = nullptr; @@ -28,7 +28,7 @@ class RestartHook : public Hook { state = State::STARTED; } - virtual void stop() override { + void stop() override { assert(state == State::STARTED); if (prev) diff --git a/lib/hooks/rms.cpp b/lib/hooks/rms.cpp index ace8db96b..3e39d5c66 100644 --- a/lib/hooks/rms.cpp +++ b/lib/hooks/rms.cpp @@ -78,10 +78,10 @@ class RMSHook : public MultiSignalHook { unsigned i = 0; for (auto index : signalIndices) { // Square the new value - double newValue = pow(smp->data[index].f, 2); + double const newValue = pow(smp->data[index].f, 2); // Get the old value from the history - double oldValue = smpMemory[i][smpMemoryPosition % windowSize]; + double const oldValue = smpMemory[i][smpMemoryPosition % windowSize]; // Append the new value to the history memory smpMemory[i][smpMemoryPosition % windowSize] = newValue; diff --git a/lib/hooks/skip_first.cpp b/lib/hooks/skip_first.cpp index 16c2afbcf..7a5e06df3 100644 --- a/lib/hooks/skip_first.cpp +++ b/lib/hooks/skip_first.cpp @@ -68,12 +68,12 @@ class SkipFirstHook : public Hook { throw ConfigError(json, err, "node-config-hook-skip_first"); } - virtual void start() override { + void start() override { skip_state = SkipState::STARTED; state = State::STARTED; } - virtual void restart() { skip_state = SkipState::STARTED; } + void restart() override { skip_state = SkipState::STARTED; } Hook::Reason process(struct Sample *smp) override { assert(state == State::STARTED); diff --git a/lib/hooks/stats.cpp b/lib/hooks/stats.cpp index d5c5edc2e..e45ff4eec 100644 --- a/lib/hooks/stats.cpp +++ b/lib/hooks/stats.cpp @@ -32,7 +32,7 @@ class StatsWriteHook : public Hook { state = State::PARSED; } - virtual Hook::Reason process(struct Sample *smp); + Hook::Reason process(struct Sample *smp) override; }; class StatsReadHook : public Hook { @@ -50,7 +50,7 @@ class StatsReadHook : public Hook { state = State::PARSED; } - virtual void start() override { + void start() override { assert(state == State::PREPARED); last = nullptr; @@ -58,7 +58,7 @@ class StatsReadHook : public Hook { state = State::STARTED; } - virtual void stop() override { + void stop() override { assert(state == State::STARTED); if (last) @@ -67,7 +67,7 @@ class StatsReadHook : public Hook { state = State::STOPPED; } - virtual Hook::Reason process(struct Sample *smp); + Hook::Reason process(struct Sample *smp) override; }; class StatsHook : public Hook { @@ -109,7 +109,7 @@ class StatsHook : public Hook { StatsHook &operator=(const StatsHook &) = delete; StatsHook(const StatsHook &) = delete; - virtual void start() override { + void start() override { assert(state == State::PREPARED); if (!uri.empty()) { @@ -121,7 +121,7 @@ class StatsHook : public Hook { state = State::STARTED; } - virtual void stop() override { + void stop() override { assert(state == State::STARTED); stats->print(uri.empty() ? stdout : output, format, verbose); @@ -132,7 +132,7 @@ class StatsHook : public Hook { state = State::STOPPED; } - virtual void restart() { + void restart() override { assert(state == State::STARTED); stats->reset(); @@ -146,7 +146,7 @@ class StatsHook : public Hook { return Hook::Reason::OK; } - virtual void periodic() override { + void periodic() override { assert(state == State::STARTED); stats->printPeriodic(uri.empty() ? stdout : output, format, node); @@ -197,7 +197,7 @@ class StatsHook : public Hook { }; Hook::Reason StatsWriteHook::process(struct Sample *smp) { - timespec now = time_now(); + timespec const now = time_now(); parent->stats->update(Stats::Metric::AGE, time_delta(&smp->ts.received, &now)); @@ -221,7 +221,7 @@ Hook::Reason StatsReadHook::process(struct Sample *smp) { time_delta(&smp->ts.origin, &smp->ts.received)); if (smp->flags & last->flags & (int)SampleFlags::HAS_SEQUENCE) { - int dist = smp->sequence - (int32_t)last->sequence; + int const dist = smp->sequence - (int32_t)last->sequence; if (dist != 1) parent->stats->update(Stats::Metric::SMPS_REORDERED, dist); } diff --git a/lib/kernel/if.cpp b/lib/kernel/if.cpp index 71ae1a9d5..b26ec65a0 100644 --- a/lib/kernel/if.cpp +++ b/lib/kernel/if.cpp @@ -32,7 +32,7 @@ Interface::Interface(struct rtnl_link *link, int aff) : nl_link(link), tc_qdisc(nullptr), affinity(aff) { logger = Log::get(fmt::format("kernel:if:{}", getName())); - int n = getIRQs(); + int const n = getIRQs(); if (n) logger->warn("Did not found any interrupts"); @@ -116,7 +116,7 @@ std::string Interface::getName() const { Interface *Interface::getEgress(struct sockaddr *sa, SuperNode *sn) { struct rtnl_link *link; - Logger logger = Log::get("kernel:if"); + Logger const logger = Log::get("kernel:if"); auto &interfaces = sn->getInterfaces(); auto affinity = sn->getAffinity(); @@ -177,7 +177,7 @@ int Interface::setAffinity(int affinity) { CpuSet cset_pin(affinity); for (int irq : irqs) { - std::string filename = fmt::format("/proc/irq/{}/smp_affinity", irq); + std::string const filename = fmt::format("/proc/irq/{}/smp_affinity", irq); file = fopen(filename.c_str(), "w"); if (file) { diff --git a/lib/kernel/tc_netem.cpp b/lib/kernel/tc_netem.cpp index 1a539ee10..08661d9d8 100644 --- a/lib/kernel/tc_netem.cpp +++ b/lib/kernel/tc_netem.cpp @@ -60,9 +60,9 @@ static int set_delay_distribution(struct rtnl_qdisc *qdisc, json_t *json) { else if (json_is_array(json)) { json_t *elm; size_t idx; - size_t len = json_array_size(json); + size_t const len = json_array_size(json); - int16_t *data = new int16_t[len]; + auto data = std::make_unique(len); if (!data) throw MemoryAllocationError(); @@ -73,7 +73,7 @@ static int set_delay_distribution(struct rtnl_qdisc *qdisc, json_t *json) { data[idx] = json_integer_value(elm); } - return rtnl_netem_set_delay_distribution_data(qdisc, data, len); + return rtnl_netem_set_delay_distribution_data(qdisc, data.get(), len); } return 0; @@ -118,7 +118,7 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { } if (json_delay_correlation) { - double dval = json_number_value(json_delay_correlation); + double const dval = json_number_value(json_delay_correlation); if (!json_is_number(json_delay_correlation) || dval < 0 || dval > 100) throw ConfigError(json_delay_correlation, @@ -164,7 +164,7 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { } if (json_loss) { - double dval = json_number_value(json_loss); + double const dval = json_number_value(json_loss); if (!json_is_number(json_loss) || dval < 0 || dval > 100) throw ConfigError(json_loss, "Setting 'loss' must be a positive integer " @@ -177,7 +177,7 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { } if (json_duplicate) { - double dval = json_number_value(json_duplicate); + double const dval = json_number_value(json_duplicate); if (!json_is_number(json_duplicate) || dval < 0 || dval > 100) throw ConfigError(json_duplicate, @@ -191,7 +191,7 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { } if (json_corruption) { - double dval = json_number_value(json_corruption); + double const dval = json_number_value(json_corruption); if (!json_is_number(json_corruption) || dval < 0 || dval > 100) throw ConfigError(json_corruption, diff --git a/lib/mapping.cpp b/lib/mapping.cpp index 5fec8fb31..0e1893d86 100644 --- a/lib/mapping.cpp +++ b/lib/mapping.cpp @@ -22,7 +22,7 @@ using namespace villas::utils; int MappingEntry::parseString(const std::string &str) { std::smatch mr; - std::regex re(RE_MAPPING); + std::regex const re(RE_MAPPING); if (!std::regex_match(str, mr, re)) goto invalid_format; @@ -223,7 +223,7 @@ int MappingEntry::prepare(NodeList &nodes) { } end: - if (length < 0) + if (node != nullptr && length < 0) // TODO: What is this code supposed to do? length = node->getInputSignals()->size(); return 0; diff --git a/lib/memory.cpp b/lib/memory.cpp index 9f454f288..5a679f85e 100644 --- a/lib/memory.cpp +++ b/lib/memory.cpp @@ -40,7 +40,7 @@ int villas::node::memory::init(int hugepages) { if (ret < 0) return ret; - size_t lock_sz = kernel::getHugePageSize() * hugepages; + size_t const lock_sz = kernel::getHugePageSize() * hugepages; ret = lock(lock_sz); if (ret) diff --git a/lib/memory/managed.cpp b/lib/memory/managed.cpp index e0be1c5b9..709f9d4e1 100644 --- a/lib/memory/managed.cpp +++ b/lib/memory/managed.cpp @@ -36,11 +36,11 @@ static struct Allocation *managed_alloc(size_t len, size_t alignment, char *cptr = (char *)block + sizeof(struct Block); size_t avail = block->length; - uintptr_t uptr = (uintptr_t)cptr; + uintptr_t const uptr = (uintptr_t)cptr; /* Check alignment first; leave a gap at start of block to assure * alignment if necessary */ - uintptr_t rem = uptr % alignment; + uintptr_t const rem = uptr % alignment; uintptr_t gap = 0; if (rem != 0) { gap = alignment - rem; diff --git a/lib/node.cpp b/lib/node.cpp index b7453eb4b..226383833 100644 --- a/lib/node.cpp +++ b/lib/node.cpp @@ -140,7 +140,7 @@ int Node::parse(json_t *json) { struct { const char *str; - struct NodeDirection *dir; + class NodeDirection *dir; } dirs[] = {{"in", &in}, {"out", &out}}; const char *fields[] = {"signals", "builtin", "vectorize", "hooks"}; @@ -281,7 +281,7 @@ int Node::read(struct Sample *smps[], unsigned cnt) { #ifdef WITH_HOOKS // Run read hooks - int rread = in.hooks.process(smps, nread); + int const rread = in.hooks.process(smps, nread); if (rread < 0) return rread; @@ -314,7 +314,7 @@ int Node::write(struct Sample *smps[], unsigned cnt) { #ifdef WITH_HOOKS // Run write hooks - int hook_cnt = out.hooks.process(smps, cnt); + int const hook_cnt = out.hooks.process(smps, cnt); if (hook_cnt <= 0) return hook_cnt; cnt = hook_cnt; @@ -395,7 +395,7 @@ unsigned Node::getOutputSignalsMaxCount() const { } bool Node::isValidName(const std::string &name) { - std::regex re(RE_NODE_NAME); + std::regex const re(RE_NODE_NAME); return std::regex_match(name, re); } diff --git a/lib/node_compat.cpp b/lib/node_compat.cpp index 02fcd759c..d7a793a4a 100644 --- a/lib/node_compat.cpp +++ b/lib/node_compat.cpp @@ -21,7 +21,7 @@ NodeCompat::NodeCompat(NodeCompatType *vt, const uuid_t &id, memset(_vd, 0, _vt->size); - int ret = _vt->init ? _vt->init(this) : 0; + int const ret = _vt->init ? _vt->init(this) : 0; if (ret) throw RuntimeError("Failed to initialize node"); } @@ -33,7 +33,7 @@ NodeCompat::NodeCompat(const NodeCompat &n) : Node(n) { memcpy(_vd, n._vd, _vt->size); - int ret = _vt->init ? _vt->init(this) : 0; + int const ret = _vt->init ? _vt->init(this) : 0; if (ret) throw RuntimeError("Failed to initialize node"); } @@ -66,7 +66,7 @@ NodeCompat::~NodeCompat() { int NodeCompat::prepare() { assert(state == State::CHECKED); - int ret = _vt->prepare ? _vt->prepare(this) : 0; + int const ret = _vt->prepare ? _vt->prepare(this) : 0; if (ret) return ret; @@ -226,7 +226,7 @@ Node *NodeCompatFactory::make(const uuid_t &id, const std::string &name) { int NodeCompatFactory::start(SuperNode *sn) { assert(state == State::INITIALIZED); - int ret = _vt->type.start ? _vt->type.start(sn) : 0; + int const ret = _vt->type.start ? _vt->type.start(sn) : 0; if (ret) return ret; @@ -236,7 +236,7 @@ int NodeCompatFactory::start(SuperNode *sn) { int NodeCompatFactory::stop() { assert(state == State::STARTED); - int ret = _vt->type.stop ? _vt->type.stop() : 0; + int const ret = _vt->type.stop ? _vt->type.stop() : 0; if (ret) return ret; diff --git a/lib/node_direction.cpp b/lib/node_direction.cpp index 39088b014..908745fef 100644 --- a/lib/node_direction.cpp +++ b/lib/node_direction.cpp @@ -100,9 +100,9 @@ int NodeDirection::parse(json_t *json) { #ifdef WITH_HOOKS if (json_hooks) { - int m = direction == NodeDirection::Direction::OUT - ? (int)Hook::Flags::NODE_WRITE - : (int)Hook::Flags::NODE_READ; + int const m = direction == NodeDirection::Direction::OUT + ? (int)Hook::Flags::NODE_WRITE + : (int)Hook::Flags::NODE_READ; hooks.parse(json_hooks, m, nullptr, node); } @@ -124,10 +124,10 @@ void NodeDirection::check() { int NodeDirection::prepare() { #ifdef WITH_HOOKS - int t = direction == NodeDirection::Direction::OUT - ? (int)Hook::Flags::NODE_WRITE - : (int)Hook::Flags::NODE_READ; - int m = builtin ? t | (int)Hook::Flags::BUILTIN : 0; + int const t = direction == NodeDirection::Direction::OUT + ? (int)Hook::Flags::NODE_WRITE + : (int)Hook::Flags::NODE_READ; + int const m = builtin ? t | (int)Hook::Flags::BUILTIN : 0; hooks.prepare(signals, m, nullptr, node); #endif // WITH_HOOKS diff --git a/lib/nodes/amqp.cpp b/lib/nodes/amqp.cpp index 07da7a5a6..9ffaff255 100644 --- a/lib/nodes/amqp.cpp +++ b/lib/nodes/amqp.cpp @@ -35,7 +35,7 @@ static void amqp_default_ssl_info(struct amqp_ssl_info *s) { } static amqp_bytes_t amqp_bytes_strdup(const char *str) { - size_t len = strlen(str) + 1; + size_t const len = strlen(str) + 1; amqp_bytes_t buf = amqp_bytes_malloc(len); memcpy(buf.bytes, str, len); @@ -345,7 +345,7 @@ int villas::node::amqp_write(NodeCompat *n, struct Sample *const smps[], if (ret <= 0) return -1; - amqp_bytes_t message = {.len = wbytes, .bytes = data}; + amqp_bytes_t const message = {.len = wbytes, .bytes = data}; // Send message ret = amqp_basic_publish(a->producer, 1, a->exchange, a->routing_key, 0, 0, @@ -411,5 +411,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.write = amqp_write; p.poll_fds = amqp_poll_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/can.cpp b/lib/nodes/can.cpp index f9e66478a..19e8bc5d3 100644 --- a/lib/nodes/can.cpp +++ b/lib/nodes/can.cpp @@ -189,7 +189,8 @@ int villas::node::can_start(NodeCompat *n) { if (c->socket < 0) throw SystemError("Error while opening CAN socket"); - strcpy(ifr.ifr_name, c->interface_name); + strncpy(ifr.ifr_name, c->interface_name, IFNAMSIZ); + ifr.ifr_name[IFNAMSIZ - 1] = 0; ret = ioctl(c->socket, SIOCGIFINDEX, &ifr); if (ret != 0) @@ -357,7 +358,7 @@ int villas::node::can_read(NodeCompat *n, struct Sample *const smps[], unsigned cnt) { int ret = 0; int nbytes; - unsigned nread = 0; + unsigned const nread = 0; struct can_frame frame; struct timeval tv; bool found_id = false; @@ -424,18 +425,13 @@ int villas::node::can_write(NodeCompat *n, struct Sample *const smps[], unsigned cnt) { int nbytes; unsigned nwrite; - struct can_frame *frame; size_t fsize = 0; // number of frames in use auto *c = n->getData(); assert(cnt >= 1 && smps[0]->capacity >= 1); - frame = (struct can_frame *)calloc(sizeof(struct can_frame), - n->getOutputSignals()->size()); - if (!frame) { - throw MemoryAllocationError(); - } + auto frame = std::make_unique(n->getOutputSignals()->size()); for (nwrite = 0; nwrite < cnt; nwrite++) { for (size_t i = 0; i < n->getOutputSignals()->size(); i++) { @@ -514,5 +510,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.write = can_write; p.poll_fds = can_poll_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/comedi.cpp b/lib/nodes/comedi.cpp index 4842021e2..03e7f8b06 100644 --- a/lib/nodes/comedi.cpp +++ b/lib/nodes/comedi.cpp @@ -206,7 +206,7 @@ static int comedi_start_in(NodeCompat *n) { cmd.chanlist_len = d->chanlist_len; // First run might change command, second should return successfully - ret = comedi_command_test(c->dev, &cmd); + comedi_command_test(c->dev, &cmd); ret = comedi_command_test(c->dev, &cmd); if (ret < 0) throw RuntimeError("Invalid command for input subdevice"); @@ -334,7 +334,8 @@ static int comedi_start_out(NodeCompat *n) { // Preload comedi output buffer for (unsigned i = 0; i < d->buffer_size / local_buffer_size; i++) { - size_t written = write(comedi_fileno(c->dev), d->buffer, local_buffer_size); + size_t const written = + write(comedi_fileno(c->dev), d->buffer, local_buffer_size); if (written != local_buffer_size) { throw RuntimeError("Cannot preload Comedi buffer"); } @@ -447,7 +448,7 @@ int villas::node::comedi_start(NodeCompat *n) { comedi_start_common(n); if (c->in.present) { - int ret = comedi_start_in(n); + int const ret = comedi_start_in(n); if (ret) return ret; @@ -455,7 +456,7 @@ int villas::node::comedi_start(NodeCompat *n) { } if (c->out.present) { - int ret = comedi_start_out(n); + int const ret = comedi_start_out(n); if (ret) return ret; @@ -562,7 +563,7 @@ int villas::node::comedi_read(NodeCompat *n, struct Sample *const smps[], (int)SampleFlags::HAS_SEQUENCE; smps[i]->sequence = d->counter / d->chanlist_len; - struct timespec offset = + struct timespec const offset = time_from_double(d->counter * 1.0 / d->sample_rate_hz); smps[i]->ts.origin = time_add(&d->started, &offset); @@ -846,7 +847,7 @@ int villas::node::comedi_write(NodeCompat *n, struct Sample *const smps[], n->logger->warn("Comedi buffer is full"); return 0; } else { - struct timespec now = time_now(); + struct timespec const now = time_now(); if (time_delta(&d->last_debug, &now) >= 1) { n->logger->debug( "Comedi write buffer: {} VILLAS samples ({}% of buffer)", @@ -1004,5 +1005,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.write = comedi_write; p.poll_fds = comedi_poll_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/ethercat.cpp b/lib/nodes/ethercat.cpp index 424ddef23..f7fcbbfb1 100644 --- a/lib/nodes/ethercat.cpp +++ b/lib/nodes/ethercat.cpp @@ -67,7 +67,7 @@ static void ethercat_cyclic_task(NodeCompat *n) { // Read process data for (unsigned i = 0; i < smp->length; i++) { - int16_t ain_value = EC_READ_S16(w->domain_pd + w->in.offsets[i]); + int16_t const ain_value = EC_READ_S16(w->domain_pd + w->in.offsets[i]); smp->data[i].f = w->in.range * (float)ain_value / INT16_MAX; } @@ -80,7 +80,7 @@ static void ethercat_cyclic_task(NodeCompat *n) { smp = w->send.exchange(nullptr); for (unsigned i = 0; i < w->out.num_channels; i++) { - int16_t aout_value = (smp->data[i].f / w->out.range) * INT16_MAX; + int16_t const aout_value = (smp->data[i].f / w->out.range) * INT16_MAX; EC_WRITE_S16(w->domain_pd + w->out.offsets[i], aout_value); } @@ -435,5 +435,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.write = ethercat_write; p.poll_fds = ethercat_poll_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/example.cpp b/lib/nodes/example.cpp index 0c16b7917..368d94d37 100644 --- a/lib/nodes/example.cpp +++ b/lib/nodes/example.cpp @@ -39,8 +39,8 @@ int ExampleNode::parse(json_t *json) { const char *setting2_str = nullptr; json_error_t err; - int ret = json_unpack_ex(json, &err, 0, "{ s?: i, s?: s }", "setting1", - &setting1, "setting2", &setting2_str); + int const ret = json_unpack_ex(json, &err, 0, "{ s?: i, s?: s }", "setting1", + &setting1, "setting2", &setting2_str); if (ret) throw ConfigError(json, err, "node-config-node-example"); diff --git a/lib/nodes/exec.cpp b/lib/nodes/exec.cpp index 6fe0cbde8..21984cdbf 100644 --- a/lib/nodes/exec.cpp +++ b/lib/nodes/exec.cpp @@ -140,7 +140,7 @@ int ExecNode::start() { if (!stream_out) return -1; - int ret = Node::start(); + int const ret = Node::start(); if (!ret) state = State::STARTED; @@ -148,7 +148,7 @@ int ExecNode::start() { } int ExecNode::stop() { - int ret = Node::stop(); + int const ret = Node::stop(); if (ret) return ret; diff --git a/lib/nodes/file.cpp b/lib/nodes/file.cpp index 3b6166869..c7a779af2 100644 --- a/lib/nodes/file.cpp +++ b/lib/nodes/file.cpp @@ -42,7 +42,7 @@ static struct timespec file_calc_offset(const struct timespec *first, const struct timespec *epoch, enum file::EpochMode mode) { // Get current time - struct timespec now = time_now(); + struct timespec const now = time_now(); struct timespec offset; // Set offset depending on epoch @@ -272,6 +272,7 @@ int villas::node::file_start(NodeCompat *n) { // Get timestamp of first line if (f->epoch_mode != file::EpochMode::ORIGINAL) { rewind(f->stream_in); + (void)errno; // TODO: should we handle errors from rewind? if (feof(f->stream_in)) { n->logger->warn("Empty file"); @@ -290,6 +291,7 @@ int villas::node::file_start(NodeCompat *n) { } rewind(f->stream_in); + (void)errno; // TODO: should we handle rewind errors? // Fast-forward struct Sample *smp = sample_alloc_mem(n->getInputSignals(false)->size()); @@ -330,6 +332,7 @@ int villas::node::file_read(NodeCompat *n, struct Sample *const smps[], f->offset = file_calc_offset(&f->first, &f->epoch, f->epoch_mode); rewind(f->stream_in); + (void)errno; // should we handle rewind errors? goto retry; case file::EOFBehaviour::SUSPEND: @@ -465,5 +468,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.write = file_write; p.poll_fds = file_poll_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/fpga.cpp b/lib/nodes/fpga.cpp index 45f1e3f24..3d1efeeb3 100644 --- a/lib/nodes/fpga.cpp +++ b/lib/nodes/fpga.cpp @@ -348,7 +348,7 @@ int FpgaNode::slowWrite(Sample *smps[], unsigned cnt) { mem[i] = smps[0]->data[i].f; } - bool state = dma->write(*blockTx, smp->length * sizeof(float)); + bool const state = dma->write(*blockTx, smp->length * sizeof(float)); if (!state) { return -1; } @@ -365,7 +365,7 @@ int FpgaNode::slowWrite(Sample *smps[], unsigned cnt) { std::vector FpgaNode::getPollFDs() { if (!lowLatencyMode && card && !card->polling) { - std::shared_ptr pciecard = + std::shared_ptr const pciecard = std::dynamic_pointer_cast(card); return pciecard->vfioDevice->getEventfdList(); } else { diff --git a/lib/nodes/iec60870.cpp b/lib/nodes/iec60870.cpp index e28f1d952..e45a503c6 100644 --- a/lib/nodes/iec60870.cpp +++ b/lib/nodes/iec60870.cpp @@ -21,8 +21,8 @@ using namespace villas::node::iec60870; using namespace std::literals::chrono_literals; static CP56Time2a timespec_to_cp56time2a(timespec time) { - time_t time_ms = static_cast(time.tv_sec) * 1000 + - static_cast(time.tv_nsec) / 1000000; + time_t const time_ms = static_cast(time.tv_sec) * 1000 + + static_cast(time.tv_nsec) / 1000000; return CP56Time2a_createFromMsTimestamp(NULL, time_ms); } @@ -155,7 +155,7 @@ ASDUData::checkASDU(CS101_ASDU const &asdu) const { switch (typeWithoutTimestamp()) { case ASDUData::SCALED_INT: { auto scaled_int = reinterpret_cast(io); - int scaled_int_value = MeasuredValueScaled_getValue(scaled_int); + int const scaled_int_value = MeasuredValueScaled_getValue(scaled_int); signal_data.i = static_cast(scaled_int_value); quality = MeasuredValueScaled_getQuality(scaled_int); break; @@ -163,7 +163,7 @@ ASDUData::checkASDU(CS101_ASDU const &asdu) const { case ASDUData::NORMALIZED_FLOAT: { auto normalized_float = reinterpret_cast(io); - float normalized_float_value = + float const normalized_float_value = MeasuredValueNormalized_getValue(normalized_float); signal_data.f = static_cast(normalized_float_value); quality = MeasuredValueNormalized_getQuality(normalized_float); @@ -172,7 +172,7 @@ ASDUData::checkASDU(CS101_ASDU const &asdu) const { case ASDUData::DOUBLE_POINT: { auto double_point = reinterpret_cast(io); - DoublePointValue double_point_value = + DoublePointValue const double_point_value = DoublePointInformation_getValue(double_point); signal_data.i = static_cast(double_point_value); quality = DoublePointInformation_getQuality(double_point); @@ -181,7 +181,8 @@ ASDUData::checkASDU(CS101_ASDU const &asdu) const { case ASDUData::SINGLE_POINT: { auto single_point = reinterpret_cast(io); - bool single_point_value = SinglePointInformation_getValue(single_point); + bool const single_point_value = + SinglePointInformation_getValue(single_point); signal_data.b = static_cast(single_point_value); quality = SinglePointInformation_getQuality(single_point); break; @@ -189,7 +190,7 @@ ASDUData::checkASDU(CS101_ASDU const &asdu) const { case ASDUData::SHORT_FLOAT: { auto short_float = reinterpret_cast(io); - float short_float_value = MeasuredValueShort_getValue(short_float); + float const short_float_value = MeasuredValueShort_getValue(short_float); signal_data.f = static_cast(short_float_value); quality = MeasuredValueShort_getQuality(short_float); break; @@ -239,7 +240,7 @@ ASDUData::checkASDU(CS101_ASDU const &asdu) const { InformationObject_destroy(io); - std::optional timestamp = + std::optional const timestamp = time_cp56.has_value() ? std::optional{cp56time2a_to_timespec(*time_cp56)} : std::nullopt; @@ -252,9 +253,6 @@ ASDUData::checkASDU(CS101_ASDU const &asdu) const { bool ASDUData::addSampleToASDU(CS101_ASDU &asdu, ASDUData::Sample sample) const { -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" - std::optional timestamp = sample.timestamp.has_value() ? std::optional{timespec_to_cp56time2a(*sample.timestamp)} @@ -348,12 +346,11 @@ bool ASDUData::addSampleToASDU(CS101_ASDU &asdu, throw RuntimeError{"invalid asdu data type"}; } - bool successfully_added = CS101_ASDU_addInformationObject(asdu, io); + bool const successfully_added = CS101_ASDU_addInformationObject(asdu, io); InformationObject_destroy(io); return successfully_added; -#pragma GCC diagnostic pop } ASDUData::ASDUData(ASDUData::Descriptor const *descriptor, int ioa, diff --git a/lib/nodes/iec61850_goose.cpp b/lib/nodes/iec61850_goose.cpp index c7477c237..7fbc8ec41 100644 --- a/lib/nodes/iec61850_goose.cpp +++ b/lib/nodes/iec61850_goose.cpp @@ -106,7 +106,7 @@ MmsValue *GooseSignal::toMmsValue() const { } MmsValue *GooseSignal::newMmsBitString(uint32_t i, int size) { - auto mms_bitstring = MmsValue_newBitString(size); + auto *mms_bitstring = MmsValue_newBitString(size); MmsValue_setBitStringFromInteger(mms_bitstring, i); @@ -114,7 +114,7 @@ MmsValue *GooseSignal::newMmsBitString(uint32_t i, int size) { } MmsValue *GooseSignal::newMmsInteger(int64_t i, int size) { - auto mms_integer = MmsValue_newInteger(size); + auto *mms_integer = MmsValue_newInteger(size); switch (size) { case 8: @@ -135,7 +135,7 @@ MmsValue *GooseSignal::newMmsInteger(int64_t i, int size) { } MmsValue *GooseSignal::newMmsUnsigned(uint64_t u, int size) { - auto mms_unsigned = MmsValue_newUnsigned(size); + auto *mms_unsigned = MmsValue_newUnsigned(size); switch (size) { case 8: @@ -168,7 +168,8 @@ std::optional GooseSignal::lookupMmsType(int mms_type) { return descriptor.mms_type == mms_type; }; - auto descriptor = std::find_if(begin(descriptors), end(descriptors), check); + const auto *descriptor = + std::find_if(begin(descriptors), end(descriptors), check); if (descriptor != end(descriptors)) return &*descriptor; else @@ -181,7 +182,8 @@ GooseSignal::lookupMmsTypeName(char const *name) { return descriptor.name == name; }; - auto descriptor = std::find_if(begin(descriptors), end(descriptors), check); + const auto *descriptor = + std::find_if(begin(descriptors), end(descriptors), check); if (descriptor != end(descriptors)) return &*descriptor; else @@ -231,15 +233,15 @@ void GooseNode::onEvent(GooseSubscriber subscriber, GooseSubscriber_needsCommission(subscriber)) return; - int last_state_num = ctx.last_state_num; - int state_num = GooseSubscriber_getStNum(subscriber); + int const last_state_num = ctx.last_state_num; + int const state_num = GooseSubscriber_getStNum(subscriber); ctx.last_state_num = state_num; if (ctx.subscriber_config.trigger == InputTrigger::CHANGE && !ctx.values.empty() && state_num == last_state_num) return; - auto mms_values = GooseSubscriber_getDataSetValues(subscriber); + auto *mms_values = GooseSubscriber_getDataSetValues(subscriber); if (MmsValue_getType(mms_values) != MmsType::MMS_ARRAY) { ctx.node->logger->warn("DataSet is not an array"); @@ -249,12 +251,12 @@ void GooseNode::onEvent(GooseSubscriber subscriber, ctx.values.clear(); for (unsigned int i = 0; i < MmsValue_getArraySize(mms_values); i++) { - auto mms_value = MmsValue_getElement(mms_values, i); + auto *mms_value = MmsValue_getElement(mms_values, i); auto goose_value = GooseSignal::fromMmsValue(mms_value); ctx.values.push_back(goose_value); } - uint64_t timestamp = GooseSubscriber_getTimestamp(subscriber); + uint64_t const timestamp = GooseSubscriber_getTimestamp(subscriber); ctx.node->pushSample(timestamp); } @@ -317,7 +319,7 @@ void GooseNode::addSubscriber(GooseNode::InputEventContext &ctx) noexcept { GooseSubscriber_setListener( subscriber, [](GooseSubscriber goose_subscriber, void *event_context) { - auto context = static_cast(event_context); + auto *context = static_cast(event_context); onEvent(goose_subscriber, *context); }, &ctx); @@ -466,7 +468,7 @@ int GooseNode::_read(Sample *samples[], unsigned sample_count) { void GooseNode::publish_values(GoosePublisher publisher, std::vector &values, bool changed, int burst) noexcept { - auto data_set = LinkedList_create(); + auto *data_set = LinkedList_create(); for (auto &value : values) { LinkedList_add(data_set, value.toMmsValue()); @@ -516,7 +518,7 @@ int GooseNode::_write(Sample *samples[], unsigned sample_count) { auto lock = std::unique_lock{output.send_mutex}; for (unsigned int i = 0; i < sample_count; i++) { - auto sample = samples[i]; + auto *sample = samples[i]; for (auto &ctx : output.contexts) { bool changed = false; @@ -693,7 +695,7 @@ void GooseNode::parseInputSignals( if (ret) throw ConfigError(json, err, "node-config-node-iec61850-8-1"); - auto mapping_type = + const auto *mapping_type = GooseSignal::lookupMmsTypeName(mapping_type_name).value(); mappings.push_back(InputMapping{ @@ -745,7 +747,7 @@ void GooseNode::parsePublisherData(json_t *json, if (ret) throw ConfigError(json, err, "node-config-node-iec61850-8-1"); - auto goose_type = GooseSignal::lookupMmsTypeName(mms_type).value(); + const auto *goose_type = GooseSignal::lookupMmsTypeName(mms_type).value(); std::optional meta = std::nullopt; if (goose_type->mms_type == MmsType::MMS_BIT_STRING && bitstring_size != -1) @@ -764,9 +766,9 @@ void GooseNode::parsePublisherData(json_t *json, if (signal_str) signal = out.signals->getIndexByName(signal_str); - OutputData value = {.signal = signal, - .default_value = - GooseSignal{goose_type, signal_data, meta}}; + OutputData const value = {.signal = signal, + .default_value = + GooseSignal{goose_type, signal_data, meta}}; data.push_back(value); }; diff --git a/lib/nodes/iec61850_sv.cpp b/lib/nodes/iec61850_sv.cpp index 4cd5486d8..ce849401e 100644 --- a/lib/nodes/iec61850_sv.cpp +++ b/lib/nodes/iec61850_sv.cpp @@ -33,7 +33,7 @@ using namespace villas::node; static unsigned iec61850_sv_setup_asdu(NodeCompat *n, struct Sample *smp) { auto *i = n->getData(); - unsigned new_length = MIN(list_length(&i->out.signals), smp->length); + unsigned const new_length = MIN(list_length(&i->out.signals), smp->length); SVPublisher_ASDU_resetBuffer(i->out.asdu); SVPublisher_ASDU_enableRefrTm(i->out.asdu); @@ -78,7 +78,7 @@ static void iec61850_sv_listener(SVSubscriber subscriber, void *ctx, const char *sv_id = SVSubscriber_ASDU_getSvId(asdu); int smp_cnt = SVSubscriber_ASDU_getSmpCnt(asdu); - size_t data_size = (size_t)SVSubscriber_ASDU_getDataSize(asdu); + size_t const data_size = (size_t)SVSubscriber_ASDU_getDataSize(asdu); n->logger->debug("Received sample: sv_id={}, smp_cnt={}", sv_id, smp_cnt); @@ -94,7 +94,7 @@ static void iec61850_sv_listener(SVSubscriber subscriber, void *ctx, smp->signals = n->getInputSignals(false); if (SVSubscriber_ASDU_hasRefrTm(asdu)) { - uint64_t t = SVSubscriber_ASDU_getRefrTmAsNs(asdu); + uint64_t const t = SVSubscriber_ASDU_getRefrTmAsNs(asdu); smp->ts.origin.tv_sec = t / 1000000000; smp->ts.origin.tv_nsec = t % 1000000000; @@ -453,7 +453,7 @@ int villas::node::iec61850_sv_write(NodeCompat *n, struct Sample *const smps[], for (unsigned j = 0; j < cnt; j++) { auto *smp = smps[j]; - unsigned asdu_length = MIN(smp->length, list_length(&i->out.signals)); + unsigned const asdu_length = MIN(smp->length, list_length(&i->out.signals)); if (i->out.asdu_length != asdu_length) i->out.asdu_length = iec61850_sv_setup_asdu(n, smp); @@ -525,7 +525,8 @@ int villas::node::iec61850_sv_write(NodeCompat *n, struct Sample *const smps[], SVPublisher_ASDU_setSmpCnt(i->out.asdu, smp->sequence); if (smp->flags & (int)SampleFlags::HAS_TS_ORIGIN) { - uint64_t t = smp->ts.origin.tv_sec * 1000000000 + smp->ts.origin.tv_nsec; + uint64_t const t = + smp->ts.origin.tv_sec * 1000000000 + smp->ts.origin.tv_nsec; SVPublisher_ASDU_setRefrTmNs(i->out.asdu, t); } @@ -563,5 +564,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.write = iec61850_sv_write; p.poll_fds = iec61850_sv_poll_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/infiniband.cpp b/lib/nodes/infiniband.cpp index 03c66dcb9..75f16fbd1 100644 --- a/lib/nodes/infiniband.cpp +++ b/lib/nodes/infiniband.cpp @@ -25,7 +25,7 @@ using namespace villas::utils; static int ib_disconnect(NodeCompat *n) { auto *ib = n->getData(); - struct ibv_wc wc[MAX(ib->recv_cq_size, ib->send_cq_size)]; + struct ibv_wc wc[MAX(ib->recv_cq_size, ib->send_cq_size)]; // NOLINT int wcs; n->logger->debug("Starting to clean up"); @@ -38,13 +38,13 @@ static int ib_disconnect(NodeCompat *n) { ib->conn.available_recv_wrs -= wcs; - for (int j = 0; j < wcs; j++) + for (int j = 0; j < wcs; j++) // NOLINT sample_decref((struct Sample *)(intptr_t)(wc[j].wr_id)); } // Send Queue while ((wcs = ibv_poll_cq(ib->ctx.send_cq, ib->send_cq_size, wc))) - for (int j = 0; j < wcs; j++) + for (int j = 0; j < wcs; j++) // NOLINT if (wc[j].wr_id > 0) sample_decref((struct Sample *)(intptr_t)(wc[j].wr_id)); @@ -159,10 +159,10 @@ int villas::node::ib_reverse(NodeCompat *n) { } int villas::node::ib_parse(NodeCompat *n, json_t *json) { - auto *ib = n->getData(); - throw ConfigError(json, "The infiniband node-type is currently broken!"); + auto *ib = n->getData(); + int ret; char *local = nullptr, *remote = nullptr, *lasts; const char *transport_mode = "RC"; @@ -183,17 +183,21 @@ int villas::node::ib_parse(NodeCompat *n, json_t *json) { json_t *json_out = nullptr; json_error_t err; - ret = - json_unpack_ex(json, &err, 0, "{ s?: o, s?: o, s?: s }", "in", &json_in, - "out", &json_out, "rdma_transport_mode", &transport_mode); + ret = json_unpack_ex(json, &err, 0, "{ s?: o, s?: o, s?: s }", // + "in", &json_in, // + "out", &json_out, // + "rdma_transport_mode", &transport_mode); if (ret) throw ConfigError(json, err, "node-config-node-ib"); if (json_in) { - ret = json_unpack_ex( - json_in, &err, 0, "{ s?: s, s?: i, s?: i, s?: i, s?: i}", "address", - &local, "cq_size", &recv_cq_size, "max_wrs", &max_recv_wr, "vectorize", - &vectorize_in, "buffer_subtraction", &buffer_subtraction); + ret = json_unpack_ex(json_in, &err, 0, + "{ s?: s, s?: i, s?: i, s?: i, s?: i}", // + "address", &local, // + "cq_size", &recv_cq_size, // + "max_wrs", &max_recv_wr, // + "vectorize", &vectorize_in, // + "buffer_subtraction", &buffer_subtraction); if (ret) throw ConfigError(json_in, err, "node-config-node-ib-in"); } @@ -201,12 +205,16 @@ int villas::node::ib_parse(NodeCompat *n, json_t *json) { if (json_out) { ret = json_unpack_ex( json_out, &err, 0, - "{ s?: s, s?: i, s?: i, s?: i, s?: i, s?: b, s?: i, s?: b, s?: i}", - "address", &remote, "resolution_timeout", &timeout, "cq_size", - &send_cq_size, "max_wrs", &max_send_wr, "max_inline_data", - &max_inline_data, "send_inline", &send_inline, "vectorize", - &vectorize_out, "use_fallback", &use_fallback, "periodic_signaling", - &ib->periodic_signaling); + "{ s?: s, s?: i, s?: i, s?: i, s?: i, s?: b, s?: i, s?: b, s?: i}", // + "address", &remote, // + "resolution_timeout", &timeout, // + "cq_size", &send_cq_size, // + "max_wrs", &max_send_wr, // + "max_inline_data", &max_inline_data, // + "send_inline", &send_inline, // + "vectorize", &vectorize_out, // + "use_fallback", &use_fallback, // + "periodic_signaling", &ib->periodic_signaling); if (ret) throw ConfigError(json_out, err, "node-config-node-ib-out"); @@ -770,7 +778,7 @@ int villas::node::ib_read(NodeCompat *n, struct Sample *const smps[], } // Get Memory Region - mr = memory::ib_get_mr(pool_buffer(sample_pool(smps[0]))); + mr = memory::ib_get_mr(pool_buffer(sample_pool(smps[0]))); // NOLINT for (int i = 0; i < max_wr_post; i++) { int j = 0; @@ -844,7 +852,7 @@ int villas::node::ib_read(NodeCompat *n, struct Sample *const smps[], * Furthermore, in case of an unreliable connection, a 40 byte * global routing header is transferred. This should be substracted as well. */ - int correction = + int const correction = (ib->conn.port_space == RDMA_PS_UDP) ? META_GRH_SIZE : META_SIZE; // TODO: fix release logic @@ -882,7 +890,7 @@ int villas::node::ib_write(NodeCompat *n, struct Sample *const smps[], // First, write // Get Memory Region - mr = memory::ib_get_mr(pool_buffer(sample_pool(smps[0]))); + mr = memory::ib_get_mr(pool_buffer(sample_pool(smps[0]))); // NOLINT for (sent = 0; sent < cnt; sent++) { int j = 0; @@ -1023,5 +1031,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.reverse = ib_reverse; p.memory_type = memory::ib; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/influxdb.cpp b/lib/nodes/influxdb.cpp index 9845fdd17..e6ba21494 100644 --- a/lib/nodes/influxdb.cpp +++ b/lib/nodes/influxdb.cpp @@ -194,5 +194,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.stop = influxdb_close; p.write = influxdb_write; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/kafka.cpp b/lib/nodes/kafka.cpp index 183717d27..c2d968b0e 100644 --- a/lib/nodes/kafka.cpp +++ b/lib/nodes/kafka.cpp @@ -596,5 +596,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.reverse = kafka_reverse; p.poll_fds = kafka_poll_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/loopback.cpp b/lib/nodes/loopback.cpp index 5cd411afa..54ce9cd90 100644 --- a/lib/nodes/loopback.cpp +++ b/lib/nodes/loopback.cpp @@ -33,7 +33,7 @@ LoopbackNode::~LoopbackNode() { int LoopbackNode::prepare() { assert(state == State::CHECKED); - int ret = queue_signalled_init(&queue, queuelen, &memory::mmap, mode); + int const ret = queue_signalled_init(&queue, queuelen, &memory::mmap, mode); if (ret) throw RuntimeError("Failed to initialize queue"); @@ -66,7 +66,7 @@ int LoopbackNode::_read(struct Sample *smps[], unsigned cnt) { int LoopbackNode::_write(struct Sample *smps[], unsigned cnt) { sample_incref_many(smps, cnt); - int pushed = queue_signalled_push_many(&queue, (void **)smps, cnt); + int const pushed = queue_signalled_push_many(&queue, (void **)smps, cnt); if (pushed < 0) { sample_decref_many(smps, cnt); return pushed; diff --git a/lib/nodes/loopback_internal.cpp b/lib/nodes/loopback_internal.cpp index eceed8424..1468b04e1 100644 --- a/lib/nodes/loopback_internal.cpp +++ b/lib/nodes/loopback_internal.cpp @@ -78,7 +78,7 @@ int InternalLoopbackNode::_read(struct Sample *smps[], unsigned cnt) { int InternalLoopbackNode::_write(struct Sample *smps[], unsigned cnt) { sample_incref_many(smps, cnt); - int pushed = queue_signalled_push_many(&queue, (void **)smps, cnt); + int const pushed = queue_signalled_push_many(&queue, (void **)smps, cnt); if (pushed < 0) { sample_decref_many(smps, cnt); return pushed; diff --git a/lib/nodes/modbus.cpp b/lib/nodes/modbus.cpp index 90ee4a5a5..792135670 100644 --- a/lib/nodes/modbus.cpp +++ b/lib/nodes/modbus.cpp @@ -97,14 +97,14 @@ void RegisterMappingSingle::IntegerToInteger::write(int64_t integer, double RegisterMappingSingle::IntegerToFloat::read(uint16_t const *registers) const { - int64_t integer = integer_conversion.read(registers); + int64_t const integer = integer_conversion.read(registers); return integer * scale + offset; } void RegisterMappingSingle::IntegerToFloat::write(double d, uint16_t *registers) const { - int64_t integer = (d - offset) / scale; + int64_t const integer = (d - offset) / scale; integer_conversion.write(integer, registers); } @@ -215,8 +215,8 @@ modbus_addr_t RegisterMappingSingle::num_registers() const { } uint16_t modbus::byteswap(uint16_t i) { - uint8_t low = (i & 0x00FF); - uint8_t high = (i & 0xFF00) >> 8; + uint8_t const low = (i & 0x00FF); + uint8_t const high = (i & 0xFF00) >> 8; return (low << 8) | high; } @@ -688,14 +688,14 @@ Rtu Rtu::parse(json_t *json) { int stop_bits = -1; json_error_t err; - int ret = json_unpack_ex(json, &err, 0, "{ s: s, s: s, s: i, s: i, s: i }", - "device", &device, "parity", &parity_str, "baudrate", - &baudrate, "data_bits", &data_bits, "stop_bits", - &stop_bits); + int const ret = json_unpack_ex( + json, &err, 0, "{ s: s, s: s, s: i, s: i, s: i }", "device", &device, + "parity", &parity_str, "baudrate", &baudrate, "data_bits", &data_bits, + "stop_bits", &stop_bits); if (ret) throw ConfigError(json, err, "node-config-node-modbus-rtu"); - Parity parity = parseParity(parity_str); + Parity const parity = parseParity(parity_str); return Rtu{device, parity, baudrate, data_bits, stop_bits}; } @@ -706,12 +706,14 @@ Tcp Tcp::parse(json_t *json) { int unit_int = -1; json_error_t err; - int ret = json_unpack_ex(json, &err, 0, "{ s: s, s?: i, s?: i }", "remote", - &remote, "port", &port, "unit", &unit_int); + int const ret = + json_unpack_ex(json, &err, 0, "{ s: s, s?: i, s?: i }", "remote", &remote, + "port", &port, "unit", &unit_int); if (ret) throw ConfigError(json, err, "node-config-node-modbus-tcp"); - std::optional unit = unit_int >= 0 ? std::optional(unit_int) : std::nullopt; + std::optional const unit = + unit_int >= 0 ? std::optional(unit_int) : std::nullopt; return Tcp{ .remote = remote, @@ -732,7 +734,7 @@ RegisterMappingSingle RegisterMappingSingle::parse(unsigned int index, double scale = 1.0; json_error_t err; - int ret = json_unpack_ex( + int const ret = json_unpack_ex( json, &err, 0, "{ s: i, s?: i, s?: i, s?: s, s?: s, s?: F, s?: F }", "address", &address, "bit", &bit, "integer_registers", &integer_registers, "word_endianess", &word_endianess_str, "byte_endianess", diff --git a/lib/nodes/mqtt.cpp b/lib/nodes/mqtt.cpp index d76704ff0..3e33679fd 100644 --- a/lib/nodes/mqtt.cpp +++ b/lib/nodes/mqtt.cpp @@ -507,5 +507,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.reverse = mqtt_reverse; p.poll_fds = mqtt_poll_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/nanomsg.cpp b/lib/nodes/nanomsg.cpp index 15ad6076a..4555a8d23 100644 --- a/lib/nodes/nanomsg.cpp +++ b/lib/nodes/nanomsg.cpp @@ -172,7 +172,7 @@ int villas::node::nanomsg_start(NodeCompat *n) { nn_strerror(errno)); // Subscribe to all topics - ret = nn_setsockopt(ret = m->in.socket, NN_SUB, NN_SUB_SUBSCRIBE, "", 0); + ret = nn_setsockopt(m->in.socket, NN_SUB, NN_SUB_SUBSCRIBE, "", 0); if (ret < 0) return ret; @@ -298,5 +298,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.poll_fds = nanomsg_poll_fds; p.netem_fds = nanomsg_netem_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/ngsi.cpp b/lib/nodes/ngsi.cpp index 833f9e12c..bcbd67f1c 100644 --- a/lib/nodes/ngsi.cpp +++ b/lib/nodes/ngsi.cpp @@ -418,7 +418,7 @@ static int ngsi_parse_context_response(json_t *json_response, int *code, static size_t ngsi_request_writer(void *contents, size_t size, size_t nmemb, void *userp) { - size_t realsize = size * nmemb; + size_t const realsize = size * nmemb; struct ngsi_response *mem = (struct ngsi_response *)userp; mem->data = (char *)realloc(mem->data, mem->len + realsize + 1); @@ -454,7 +454,7 @@ static int ngsi_request(CURL *handle, const char *endpoint, // We don't want to leave the handle in an invalid state pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old); - CURLcode ret = curl_easy_perform(handle); + CURLcode const ret = curl_easy_perform(handle); pthread_setcancelstate(old, nullptr); if (ret) { @@ -663,8 +663,8 @@ int villas::node::ngsi_start(NodeCompat *n) { json_t *json_entity = ngsi_build_entity( n, nullptr, 0, NGSI_ENTITY_ATTRIBUTES | NGSI_ENTITY_METADATA); - int ret = ngsi_request_context_update(i->out.curl, i->endpoint, "APPEND", - json_entity, n->logger); + int const ret = ngsi_request_context_update( + i->out.curl, i->endpoint, "APPEND", json_entity, n->logger); if (ret) throw RuntimeError("Failed to create NGSI context for node {}", n->getName()); @@ -834,5 +834,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.poll_fds = ngsi_poll_fds; p.reverse = ngsi_reverse; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/opendss.cpp b/lib/nodes/opendss.cpp index b9fcb107e..b13adb2dd 100644 --- a/lib/nodes/opendss.cpp +++ b/lib/nodes/opendss.cpp @@ -59,8 +59,9 @@ void OpenDSS::parseData(json_t *json, bool in) { json_t *a_mode = nullptr; Element ele; - int ret = json_unpack_ex(json_data, &err, 0, "{ s: s, s: s, s: o }", - "name", &name, "type", &type, "data", &a_mode); + int const ret = + json_unpack_ex(json_data, &err, 0, "{ s: s, s: s, s: o }", "name", + &name, "type", &type, "data", &a_mode); if (ret) throw ConfigError(json, err, "node-config-node-opendss"); @@ -199,7 +200,7 @@ void OpenDSS::getElementName(ElementType type, int OpenDSS::prepare() { // Start OpenDSS. - int ret = DSSI(3, 0); + int const ret = DSSI(3, 0); if (!ret) { throw SystemError("Failed to start OpenDSS"); } diff --git a/lib/nodes/redis.cpp b/lib/nodes/redis.cpp index ee9f3eb60..37c222dab 100644 --- a/lib/nodes/redis.cpp +++ b/lib/nodes/redis.cpp @@ -140,7 +140,8 @@ static int redis_get(NodeCompat *n, struct Sample *const smps[], unsigned cnt) { case RedisMode::KEY: { auto value = r->conn->context.get(r->key); if (value) { - size_t rbytes, bytes = value->size(); + size_t rbytes; + size_t const bytes = value->size(); ret = r->formatter->sscan(value->c_str(), bytes, &rbytes, smps, cnt); if (rbytes != bytes) @@ -204,7 +205,7 @@ static void redis_on_message(NodeCompat *n, const std::string &channel, n->logger->debug("Message: {}: {}", channel, msg); int alloc, scanned, pushed = 0; - unsigned cnt = n->in.vectorize; + unsigned const cnt = n->in.vectorize; struct Sample *smps[cnt]; alloc = sample_alloc_many(&r->pool, smps, cnt); @@ -598,7 +599,7 @@ int villas::node::redis_write(NodeCompat *n, struct Sample *const smps[], std::unordered_map kvs; - unsigned len = MIN(smp->signals->size(), smp->length); + unsigned const len = MIN(smp->signals->size(), smp->length); for (unsigned j = 0; j < len; j++) { const auto sig = smp->signals->getByIndex(j); const auto *data = &smp->data[j]; @@ -639,5 +640,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.write = redis_write; p.poll_fds = redis_poll_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/rtp.cpp b/lib/nodes/rtp.cpp index 964e6f1c0..77f78d35d 100644 --- a/lib/nodes/rtp.cpp +++ b/lib/nodes/rtp.cpp @@ -348,13 +348,13 @@ int villas::node::rtp_start(NodeCompat *n) { #endif } - double dt = 5.0; // TODO + double const dt = 5.0; // TODO r->aimd.rate_pid = villas::dsp::PID(dt, r->aimd.rate_source, r->aimd.rate_min, r->aimd.Kp, r->aimd.Ki, r->aimd.Kd); // Initialize RTP socket - uint16_t port = sa_port(&r->in.saddr_rtp) & ~1; + uint16_t const port = sa_port(&r->in.saddr_rtp) & ~1; ret = rtp_listen(&r->rs, IPPROTO_UDP, &r->in.saddr_rtp, port, port + 1, r->rtcp.enabled, rtp_handler, rtcp_handler, n); @@ -367,7 +367,7 @@ int villas::node::rtp_start(NodeCompat *n) { if (r->aimd.log_filename) { char fn[128]; - time_t ts = time(nullptr); + time_t const ts = time(nullptr); struct tm tm; // Convert time @@ -513,7 +513,7 @@ int villas::node::rtp_write(NodeCompat *n, struct Sample *const smps[], size_t wbytes; size_t avail; - uint32_t ts = (uint32_t)time(nullptr); + uint32_t const ts = (uint32_t)time(nullptr); retry: mbuf_set_pos(r->send_mb, RTP_HEADER_SIZE); diff --git a/lib/nodes/shmem.cpp b/lib/nodes/shmem.cpp index c502ddb02..cfa41e70f 100644 --- a/lib/nodes/shmem.cpp +++ b/lib/nodes/shmem.cpp @@ -219,5 +219,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.prepare = shmem_prepare; p.init = shmem_init; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/signal.cpp b/lib/nodes/signal.cpp index d5ce3fb24..08f822dee 100644 --- a/lib/nodes/signal.cpp +++ b/lib/nodes/signal.cpp @@ -247,7 +247,7 @@ int SignalNode::start() { if (rt) task.setRate(rate); - int ret = Node::start(); + int const ret = Node::start(); if (!ret) state = State::STARTED; @@ -258,7 +258,7 @@ int SignalNode::stop() { assert(state == State::STARTED || state == State::PAUSED || state == State::STOPPING); - int ret = Node::stop(); + int const ret = Node::stop(); if (ret) return ret; @@ -277,18 +277,19 @@ int SignalNode::_read(struct Sample *smps[], unsigned cnt) { struct Sample *t = smps[0]; struct timespec ts; - uint64_t steps, counter = sequence - sequence_init; + uint64_t steps; + uint64_t const counter = sequence - sequence_init; assert(cnt == 1); if (rt) ts = time_now(); else { - struct timespec offset = time_from_double(counter * 1.0 / rate); + struct timespec const offset = time_from_double(counter * 1.0 / rate); ts = time_add(&started, &offset); } - double running = time_delta(&started, &ts); + double const running = time_delta(&started, &ts); t->flags = (int)SampleFlags::HAS_TS_ORIGIN | (int)SampleFlags::HAS_DATA | (int)SampleFlags::HAS_SEQUENCE; diff --git a/lib/nodes/signal_v1.cpp b/lib/nodes/signal_v1.cpp index 728f80ce4..7a1c225d2 100644 --- a/lib/nodes/signal_v1.cpp +++ b/lib/nodes/signal_v1.cpp @@ -185,7 +185,7 @@ int villas::node::signal_node_parse(NodeCompat *n, json_t *json) { const char *name; }; - std::list arrays = { + std::list const arrays = { {json_frequency, &s->frequency, 1, "frequency"}, {json_amplitude, &s->amplitude, 1, "amplitude"}, {json_stddev, &s->stddev, 0.2, "stddev"}, @@ -328,14 +328,14 @@ int villas::node::signal_node_read(NodeCompat *n, struct Sample *const smps[], if (s->rt) ts = time_now(); else { - struct timespec offset = time_from_double(s->counter * 1.0 / s->rate); + struct timespec const offset = time_from_double(s->counter * 1.0 / s->rate); ts = time_add(&s->started, &offset); steps = 1; } - double running = time_delta(&s->started, &ts); + double const running = time_delta(&s->started, &ts); t->flags = (int)SampleFlags::HAS_TS_ORIGIN | (int)SampleFlags::HAS_DATA | (int)SampleFlags::HAS_SEQUENCE; @@ -471,5 +471,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.read = signal_node_read; p.poll_fds = signal_node_poll_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/socket.cpp b/lib/nodes/socket.cpp index 295fa681b..5690ed7e7 100644 --- a/lib/nodes/socket.cpp +++ b/lib/nodes/socket.cpp @@ -170,7 +170,7 @@ int villas::node::socket_check(NodeCompat *n) { if (s->in.saddr.sa.sa_family != AF_INET) throw RuntimeError("Multicast is only supported by IPv4"); - uint32_t addr = ntohl(s->multicast.mreq.imr_multiaddr.s_addr); + uint32_t const addr = ntohl(s->multicast.mreq.imr_multiaddr.s_addr); if ((addr >> 28) != 14) throw RuntimeError("Multicast group address must be within 224.0.0.0/4"); } diff --git a/lib/nodes/stats.cpp b/lib/nodes/stats.cpp index 2aa01983a..922e918a2 100644 --- a/lib/nodes/stats.cpp +++ b/lib/nodes/stats.cpp @@ -205,7 +205,7 @@ int villas::node::stats_node_read(NodeCompat *n, struct Sample *const smps[], s->task.wait(); - unsigned len = MIN(list_length(&s->signals), smps[0]->capacity); + unsigned const len = MIN(list_length(&s->signals), smps[0]->capacity); for (size_t i = 0; i < len; i++) { struct stats_node_signal *sig = @@ -252,5 +252,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.read = stats_node_read; p.poll_fds = stats_node_poll_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/temper.cpp b/lib/nodes/temper.cpp index 53289c8ab..30a3dec39 100644 --- a/lib/nodes/temper.cpp +++ b/lib/nodes/temper.cpp @@ -36,7 +36,7 @@ static NodeCompatType p; TEMPerDevice::TEMPerDevice(struct libusb_device *dev) : usb::Device(dev), scale(1.0), offset(0.0), timeout(5000) { - int ret = libusb_get_device_descriptor(dev, &desc); + int const ret = libusb_get_device_descriptor(dev, &desc); if (ret != LIBUSB_SUCCESS) throw RuntimeError("Could not get USB device descriptor: {}", libusb_strerror((enum libusb_error)ret)); @@ -166,7 +166,7 @@ TEMPerDevice *TEMPerDevice::make(struct libusb_device *dev) { bool TEMPer1Device::match(struct libusb_device *dev) { struct libusb_device_descriptor desc; - int ret = libusb_get_device_descriptor(dev, &desc); + int const ret = libusb_get_device_descriptor(dev, &desc); if (ret < 0) { Log::get("node:temper") ->warn("Could not get USB device descriptor: {}", @@ -215,7 +215,7 @@ bool TEMPer2Device::match(struct libusb_device *dev) { bool TEMPerHUMDevice::match(struct libusb_device *dev) { struct libusb_device_descriptor desc; - int ret = libusb_get_device_descriptor(dev, &desc); + int const ret = libusb_get_device_descriptor(dev, &desc); if (ret < 0) { Log::get("node:temper") ->warn("Could not get USB device descriptor: {}", @@ -235,16 +235,19 @@ int villas::node::temper_type_start(villas::node::SuperNode *sn) { devices.clear(); struct libusb_device **devs; - int cnt = libusb_get_device_list(context, &devs); + int const cnt = libusb_get_device_list(context, &devs); for (int i = 0; i < cnt; i++) { auto *dev = TEMPerDevice::make(devs[i]); + auto manufacturer = dev->getManufacturer(); + auto product = dev->getProduct(); + auto serial = dev->getSerial(); logger->debug( "Found Temper device at bus={03d}, port={03d}, vendor_id={04x}, " "product_id={04x}, manufacturer={}, product={}, serial={}", dev->getBus(), dev->getPort(), dev->getDescriptor().idVendor, - dev->getDescriptor().idProduct, dev->getManufacturer(), - dev->getProduct(), dev->getSerial()); + dev->getDescriptor().idProduct, manufacturer.c_str(), product.c_str(), + serial.c_str()); devices.push_back(dev); } @@ -305,11 +308,13 @@ int villas::node::temper_parse(NodeCompat *n, json_t *json) { char *villas::node::temper_print(NodeCompat *n) { auto *t = n->getData(); + auto product = t->device->getProduct(); + auto manufacturer = t->device->getManufacturer(); + auto serial = t->device->getSerial(); return strf("product=%s, manufacturer=%s, serial=%s humidity=%s, " "temperature=%d, usb.vendor_id=%#x, usb.product_id=%#x, " "calibration.scale=%f, calibration.offset=%f", - t->device->getProduct(), t->device->getManufacturer(), - t->device->getSerial(), + product.c_str(), manufacturer.c_str(), serial.c_str(), t->device->hasHumiditySensor() ? "yes" : "no", t->device->getNumSensors(), t->device->getDescriptor().idVendor, t->device->getDescriptor().idProduct, t->calibration.scale, @@ -401,5 +406,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.stop = temper_stop; p.read = temper_read; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/test_rtt.cpp b/lib/nodes/test_rtt.cpp index 2059a61f9..62d8bcb02 100644 --- a/lib/nodes/test_rtt.cpp +++ b/lib/nodes/test_rtt.cpp @@ -93,7 +93,7 @@ int TestRTT::prepare() { unsigned max_values = 0; // Take current for time for test case prefix - time_t ts = time(nullptr); + time_t const ts = time(nullptr); struct tm tm; gmtime_r(&ts, &tm); @@ -133,7 +133,7 @@ static enum TestRTT::Mode parseMode(const char *mode_str) { } int TestRTT::parse(json_t *json) { - int ret; + [[maybe_unused]] int ret; const char *output_str = "."; const char *prefix_str = nullptr; @@ -218,10 +218,15 @@ int TestRTT::parse(json_t *json) { json_t *json_rates = json_rates_default; json_t *json_values = json_values_default; - ret = json_unpack_ex( - json_case, &err, 0, "{ s?: o, s?: o, s?: i, s?: F, s?: s }", "rates", - &json_rates, "values", &json_values, "count", &count, "duration", - &duration, "warmup", &warmup, "cooldown", &cooldown, "mode", &mode_str); + ret = json_unpack_ex(json_case, &err, 0, + "{ s?: o, s?: o, s?: i, s?: F, s?: s }", // + "rates", &json_rates, // + "values", &json_values, // + "count", &count, // + "duration", &duration, // + "warmup", &warmup, // + "cooldown", &cooldown, // + "mode", &mode_str); if (!json_is_array(json_rates) && !json_is_number(json_rates)) throw ConfigError( @@ -269,8 +274,8 @@ int TestRTT::parse(json_t *json) { for (int rate : rates) { for (int value : values) { int count_effective; - int count_duration = duration * rate; - int count_warmup = warmup * rate; + int const count_duration = duration * rate; + int const count_warmup = warmup * rate; switch (mode) { case Mode::MIN: diff --git a/lib/nodes/uldaq.cpp b/lib/nodes/uldaq.cpp index 3cad43034..5a5917468 100644 --- a/lib/nodes/uldaq.cpp +++ b/lib/nodes/uldaq.cpp @@ -286,7 +286,7 @@ int villas::node::uldaq_parse(NodeCompat *n, json_t *json) { throw ConfigError(json, err, "node-config-node-uldaq"); if (interface_type) { - int iftype = uldaq_parse_interface_type(interface_type); + int const iftype = uldaq_parse_interface_type(interface_type); if (iftype < 0) throw ConfigError(json, "node-config-node-uldaq-interface-type", "Invalid interface type: {}", interface_type); @@ -295,7 +295,7 @@ int villas::node::uldaq_parse(NodeCompat *n, json_t *json) { } if (sample_clock_source) { - int clksrc = uldaq_parse_clock_source(sample_clock_source); + int const clksrc = uldaq_parse_clock_source(sample_clock_source); if (clksrc < 0) { throw ConfigError(json, "node-config-node-uldaq-clock_source", "Invalid clock source type: {}", sample_clock_source); @@ -530,6 +530,12 @@ int villas::node::uldaq_start(NodeCompat *n) { // Enable the event to be notified every time samples are available err = ulEnableEvent(u->device_handle, DE_ON_DATA_AVAILABLE, n->in.vectorize, uldaq_data_available, n); + if (err != ERR_NO_ERROR) { + char buf[ERR_MSG_LEN]; + ulGetErrMsg(err, buf); + throw RuntimeError("Failed to attach data event handler on DAQ device: {}", + buf); + } // Start the acquisition err = ulAInScan(u->device_handle, 0, 0, (AiInputMode)0, (Range)0, @@ -602,7 +608,7 @@ int villas::node::uldaq_read(NodeCompat *n, struct Sample *const smps[], if (u->in.status != SS_RUNNING) return -1; - size_t start_index = u->in.buffer_pos; + size_t const start_index = u->in.buffer_pos; // Wait for data available condition triggered by event callback if (start_index + n->in.vectorize * u->in.channel_count > @@ -612,10 +618,10 @@ int villas::node::uldaq_read(NodeCompat *n, struct Sample *const smps[], for (unsigned j = 0; j < cnt; j++) { struct Sample *smp = smps[j]; - long long scan_index = start_index + j * u->in.channel_count; + long long const scan_index = start_index + j * u->in.channel_count; for (unsigned i = 0; i < u->in.channel_count; i++) { - long long channel_index = (scan_index + i) % u->in.buffer_len; + long long const channel_index = (scan_index + i) % u->in.buffer_len; smp->data[i].f = u->in.buffer[channel_index]; } @@ -650,5 +656,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.stop = uldaq_stop; p.read = uldaq_read; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/nodes/webrtc.cpp b/lib/nodes/webrtc.cpp index e89026817..8bdc9ca52 100644 --- a/lib/nodes/webrtc.cpp +++ b/lib/nodes/webrtc.cpp @@ -28,8 +28,8 @@ static villas::node::Web *web; WebRTCNode::WebRTCNode(const uuid_t &id, const std::string &name) : Node(id, name), server("https://villas.k8s.eonerc.rwth-aachen.de/ws/signaling"), - peer(uuid::toString(id)), wait_seconds(0), formatter(), queue({}), - pool({}), dci({}) { + peer(uuid::toString(id)), wait_seconds(0), formatter(), queue(), pool(), + dci({}) { #if RTC_VERSION_NUM < 0x001400 dci.reliability.type = rtc::Reliability::Type::Rexmit; @@ -42,7 +42,7 @@ WebRTCNode::WebRTCNode(const uuid_t &id, const std::string &name) } WebRTCNode::~WebRTCNode() { - int ret = pool_destroy(&pool); + int const ret = pool_destroy(&pool); if (ret) logger->error("Failed to destroy pool"); } @@ -105,7 +105,7 @@ int WebRTCNode::parse(json_t *json) { throw ConfigError(json_server, "node-config-node-webrtc-ice-server", "ICE servers must be provided as STUN/TURN url."); - std::string uri = json_string_value(json_server); + std::string const uri = json_string_value(json_server); rtcConf.iceServers.emplace_back(uri); } @@ -157,7 +157,7 @@ int WebRTCNode::prepare() { } int WebRTCNode::start() { - int ret = Node::start(); + int const ret = Node::start(); if (!ret) state = State::STARTED; @@ -198,7 +198,7 @@ int WebRTCNode::_read(struct Sample *smps[], unsigned cnt) { std::vector smpt; smpt.resize(cnt); - int pulled = + int const pulled = queue_signalled_pull_many(&queue, (void **)smpt.data(), smpt.size()); sample_copy_many(smps, smpt.data(), pulled); @@ -212,7 +212,7 @@ int WebRTCNode::_write(struct Sample *smps[], unsigned cnt) { size_t wbytes; buf.resize(4 * 1024); - int ret = + int const ret = formatter->sprint((char *)buf.data(), buf.size(), &wbytes, smps, cnt); if (ret < 0) { logger->error("Failed to format payload"); diff --git a/lib/nodes/webrtc/peer_connection.cpp b/lib/nodes/webrtc/peer_connection.cpp index fca8f1359..25ea375c8 100644 --- a/lib/nodes/webrtc/peer_connection.cpp +++ b/lib/nodes/webrtc/peer_connection.cpp @@ -209,7 +209,7 @@ void PeerConnection::onConnectionStateChange(rtc::PeerConnection::State state) { case rtc::PeerConnection::State::Connected: { rtc::Candidate local, remote; - std::optional rtt = conn->rtt(); + std::optional const rtt = conn->rtt(); if (conn->getSelectedCandidatePair(&local, &remote)) { std::stringstream l, r; l << local, r << remote; diff --git a/lib/nodes/webrtc/signaling_message.cpp b/lib/nodes/webrtc/signaling_message.cpp index 71aaac5cf..74bf5c29b 100644 --- a/lib/nodes/webrtc/signaling_message.cpp +++ b/lib/nodes/webrtc/signaling_message.cpp @@ -31,9 +31,10 @@ json_t *Peer::toJson() const { Peer::Peer(json_t *json) { const char *nme = nullptr, *rem = nullptr, *ua = nullptr, *tscreat, *tsconn; - int ret = json_unpack(json, "{ s: i, s?: s, s?: s, s?: s, s?: s, s?: s }", - "id", &id, "name", &nme, "remote", &rem, "user_agent", - &ua, "created", &tscreat, "connected", &tsconn); + int const ret = + json_unpack(json, "{ s: i, s?: s, s?: s, s?: s, s?: s, s?: s }", "id", + &id, "name", &nme, "remote", &rem, "user_agent", &ua, + "created", &tscreat, "connected", &tsconn); if (ret) throw RuntimeError("Failed to decode signaling message"); @@ -168,7 +169,7 @@ SignalingMessage SignalingMessage::fromJson(json_t *json) { const char *desc = nullptr; const char *typ = nullptr; - int ret = json_unpack( + int const ret = json_unpack( json, "{ s?: o, s?: o, s?: o, s?: { s: s, s: s }, s?: { s: s, s: s } }", "servers", &rlys, "signals", &sigs, "control", &ctrl, "candidate", "spd", &cand, "mid", &mid, "description", "spd", &desc, "type", &typ); diff --git a/lib/nodes/websocket.cpp b/lib/nodes/websocket.cpp index bdf9cccc5..61c1482d7 100644 --- a/lib/nodes/websocket.cpp +++ b/lib/nodes/websocket.cpp @@ -70,10 +70,9 @@ static int websocket_connection_destroy(struct websocket_connection *c) { assert(c->state != websocket_connection::State::DESTROYED); // Return all samples to pool - int avail; struct Sample *smp; - while ((avail = queue_pull(&c->queue, (void **)&smp))) + while (queue_pull(&c->queue, (void **)&smp)) sample_decref(smp); ret = queue_destroy(&c->queue); @@ -132,7 +131,8 @@ static void websocket_connection_close(struct websocket_connection *c, int villas::node::websocket_protocol_cb(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { - int ret, recvd, pulled, cnt = 128; + int const cnt = 128; + int ret, recvd, pulled; struct websocket_connection *c = (struct websocket_connection *)user; switch (reason) { @@ -216,7 +216,7 @@ int villas::node::websocket_protocol_cb(struct lws *wsi, c->toString()); { - std::lock_guard guard(connections_lock); + std::lock_guard const guard(connections_lock); connections.push_back(c); } @@ -239,7 +239,7 @@ int villas::node::websocket_protocol_cb(struct lws *wsi, } { - std::lock_guard guard(connections_lock); + std::lock_guard const guard(connections_lock); connections.remove(c); } @@ -296,7 +296,7 @@ int villas::node::websocket_protocol_cb(struct lws *wsi, // We dont try to parse the frame yet, as we have to wait for the remaining fragments if (lws_is_final_fragment(wsi)) { - struct timespec ts_recv = time_now(); + struct timespec const ts_recv = time_now(); auto *n = c->node; int avail, enqueued; @@ -369,7 +369,7 @@ int villas::node::websocket_init(NodeCompat *n) { w->wait = false; - int ret = list_init(&w->destinations); + int const ret = list_init(&w->destinations); if (ret) return ret; @@ -392,7 +392,7 @@ int villas::node::websocket_start(NodeCompat *n) { for (size_t i = 0; i < list_length(&w->destinations); i++) { const char *format; auto *d = (struct websocket_destination *)list_at(&w->destinations, i); - auto *c = new struct websocket_connection; + auto c = std::make_unique(); if (!c) throw MemoryAllocationError(); @@ -413,7 +413,7 @@ int villas::node::websocket_start(NodeCompat *n) { d->info.context = web->getContext(); d->info.vhost = web->getVHost(); - d->info.userdata = c; + d->info.userdata = c.release(); lws_client_connect_via_info(&d->info); } @@ -423,7 +423,7 @@ int villas::node::websocket_start(NodeCompat *n) { unsigned connected = 0, total = list_length(&w->destinations); do { { - std::lock_guard guard(connections_lock); + std::lock_guard const guard(connections_lock); connected = 0; for (auto *c : connections) { @@ -452,7 +452,7 @@ int villas::node::websocket_stop(NodeCompat *n) { unsigned open_connections; do { { - std::lock_guard guard(connections_lock); + std::lock_guard const guard(connections_lock); open_connections = 0; for (auto *c : connections) { @@ -533,7 +533,7 @@ int villas::node::websocket_write(NodeCompat *n, struct Sample *const smps[], sample_copy_many(cpys, smps, avail); { - std::lock_guard guard(connections_lock); + std::lock_guard const guard(connections_lock); for (auto *c : connections) { if (c->node == n) websocket_connection_write(c, cpys, cnt); diff --git a/lib/nodes/zeromq.cpp b/lib/nodes/zeromq.cpp index 98bc19ea8..9478cb47d 100644 --- a/lib/nodes/zeromq.cpp +++ b/lib/nodes/zeromq.cpp @@ -40,7 +40,7 @@ static int get_monitor_event(void *monitor, int *value, char **address) { assert(zmq_msg_more(&msg)); uint8_t *data = (uint8_t *)zmq_msg_data(&msg); - uint16_t event = *(uint16_t *)(data); + uint16_t const event = *(uint16_t *)(data); if (value) *value = *(uint32_t *)(data + 2); @@ -53,7 +53,7 @@ static int get_monitor_event(void *monitor, int *value, char **address) { if (address) { uint8_t *data = (uint8_t *)zmq_msg_data(&msg); - size_t size = zmq_msg_size(&msg); + size_t const size = zmq_msg_size(&msg); *address = (char *)malloc(size + 1); memcpy(*address, data, size); *address[size] = 0; @@ -434,7 +434,7 @@ int villas::node::zeromq_start(NodeCompat *n) { // Wait for all connections to be connected for (auto d : dirs) { while (d->pending > 0) { - int evt = d->bind ? ZMQ_EVENT_LISTENING : ZMQ_EVENT_CONNECTED; + int const evt = d->bind ? ZMQ_EVENT_LISTENING : ZMQ_EVENT_CONNECTED; ret = get_monitor_event(d->mon_socket, nullptr, nullptr); if (ret == evt) @@ -550,7 +550,7 @@ int villas::node::zeromq_write(NodeCompat *n, struct Sample *const smps[], if (ret <= 0) return -1; - ret = zmq_msg_init_size(&m, wbytes); + zmq_msg_init_size(&m, wbytes); if (z->out.filter) { switch (z->pattern) { @@ -641,5 +641,5 @@ __attribute__((constructor(110))) static void register_plugin() { p.poll_fds = zeromq_poll_fds; p.netem_fds = zeromq_netem_fds; - static NodeCompatFactory ncp(&p); + static NodeCompatFactory const ncp(&p); } diff --git a/lib/path.cpp b/lib/path.cpp index 2657fdb95..87dd9c1f1 100644 --- a/lib/path.cpp +++ b/lib/path.cpp @@ -129,7 +129,7 @@ void Path::startPoll() { ps->getNode()->getName()); // This slot is only used if it is not masked - struct pollfd pfd = {.fd = fd, .events = POLLIN}; + struct pollfd const pfd = {.fd = fd, .events = POLLIN}; pfds.push_back(pfd); } @@ -139,7 +139,7 @@ void Path::startPoll() { if (rate > 0) { timeout.setRate(rate); - struct pollfd pfd = {.fd = timeout.getFD(), .events = POLLIN}; + struct pollfd const pfd = {.fd = timeout.getFD(), .events = POLLIN}; if (pfd.fd < 0) throw RuntimeError("Failed to get file descriptor for timer of path {}", @@ -167,7 +167,7 @@ void Path::prepare(NodeList &nodes) { // Create path sources std::map psm; - unsigned i = 0, j = 0; + unsigned j = 0; for (auto me : mappings) { Node *n = me->node; PathSource::Ptr ps; @@ -182,7 +182,7 @@ void Path::prepare(NodeList &nodes) { * A secondary path source uses an internal loopback node / queue * to forward samples from on path to another. */ - bool isSecondary = n->sources.size() > 0; + bool const isSecondary = n->sources.size() > 0; // Create new path source if (isSecondary) { @@ -223,7 +223,7 @@ void Path::prepare(NodeList &nodes) { psm[n] = ps; } - SignalList::Ptr sigs = me->node->getInputSignals(); + SignalList::Ptr const sigs = me->node->getInputSignals(); // Update signals of path for (unsigned j = 0; j < (unsigned)me->length; j++) { @@ -251,7 +251,6 @@ void Path::prepare(NodeList &nodes) { } ps->mappings.push_back(me); - i++; } // Prepare path destinations @@ -289,7 +288,8 @@ void Path::prepare(NodeList &nodes) { #ifdef WITH_HOOKS // Prepare path hooks - int m = builtin ? (int)Hook::Flags::PATH | (int)Hook::Flags::BUILTIN : 0; + int const m = + builtin ? (int)Hook::Flags::PATH | (int)Hook::Flags::BUILTIN : 0; // Add internal hooks if they are not already in the list hooks.prepare(signals, m, this, nullptr); @@ -298,7 +298,7 @@ void Path::prepare(NodeList &nodes) { // Prepare pool auto osigs = getOutputSignals(); - unsigned pool_size = MAX(1UL, destinations.size()) * queuelen; + unsigned const pool_size = MAX(1UL, destinations.size()) * queuelen; ret = pool_init(&pool, pool_size, SAMPLE_LENGTH(osigs->size()), pool_mt); if (ret) diff --git a/lib/path_source.cpp b/lib/path_source.cpp index 9d7dc0d04..419c996d3 100644 --- a/lib/path_source.cpp +++ b/lib/path_source.cpp @@ -23,7 +23,7 @@ using namespace villas::node; PathSource::PathSource(Path *p, Node *n) : node(n), path(p), masked(false) { int ret; - int pool_size = MAX(DEFAULT_QUEUE_LENGTH, 20 * node->in.vectorize); + int const pool_size = MAX(DEFAULT_QUEUE_LENGTH, 20 * node->in.vectorize); ret = pool_init(&pool, pool_size, SAMPLE_LENGTH(node->getInputSignalsMaxCount()), node->getMemoryType()); @@ -193,7 +193,7 @@ MasterPathSource::MasterPathSource(Path *p, Node *n) : PathSource(p, n) {} void MasterPathSource::writeToSecondaries(struct Sample *smps[], unsigned cnt) { for (auto sps : secondaries) { - int sent = sps->getNode()->write(smps, cnt); + int const sent = sps->getNode()->write(smps, cnt); if (sent < 0) throw RuntimeError("Failed to write secondary path source {} of path {}", sps->getNode()->getName(), path->toString()); diff --git a/lib/queue_signalled.cpp b/lib/queue_signalled.cpp index 2f38ef0b8..54ca07782 100644 --- a/lib/queue_signalled.cpp +++ b/lib/queue_signalled.cpp @@ -188,12 +188,13 @@ int villas::node::queue_signalled_push_many(struct CQueueSignalled *qs, } int villas::node::queue_signalled_pull(struct CQueueSignalled *qs, void **ptr) { + auto mode = qs->mode; int pulled = 0; // Make sure that qs->mutex is unlocked if this thread gets cancelled pthread_cleanup_push(queue_signalled_cleanup, qs); - if (qs->mode == QueueSignalledMode::PTHREAD) + if (mode == QueueSignalledMode::PTHREAD) pthread_mutex_lock(&qs->pthread.mutex); while (!pulled) { @@ -201,12 +202,12 @@ int villas::node::queue_signalled_pull(struct CQueueSignalled *qs, void **ptr) { if (pulled < 0) break; else if (pulled == 0) { - if (qs->mode == QueueSignalledMode::PTHREAD) + if (mode == QueueSignalledMode::PTHREAD) pthread_cond_wait(&qs->pthread.ready, &qs->pthread.mutex); - else if (qs->mode == QueueSignalledMode::POLLING) + else if (mode == QueueSignalledMode::POLLING) continue; // Try again #ifdef HAS_EVENTFD - else if (qs->mode == QueueSignalledMode::EVENTFD) { + else if (mode == QueueSignalledMode::EVENTFD) { int ret; uint64_t cntr; ret = read(qs->eventfd, &cntr, sizeof(cntr)); @@ -229,12 +230,13 @@ int villas::node::queue_signalled_pull(struct CQueueSignalled *qs, void **ptr) { int villas::node::queue_signalled_pull_many(struct CQueueSignalled *qs, void *ptr[], size_t cnt) { + auto mode = qs->mode; int pulled = 0; // Make sure that qs->mutex is unlocked if this thread gets cancelled pthread_cleanup_push(queue_signalled_cleanup, qs); - if (qs->mode == QueueSignalledMode::PTHREAD) + if (mode == QueueSignalledMode::PTHREAD) pthread_mutex_lock(&qs->pthread.mutex); while (!pulled) { @@ -242,12 +244,12 @@ int villas::node::queue_signalled_pull_many(struct CQueueSignalled *qs, if (pulled < 0) break; else if (pulled == 0) { - if (qs->mode == QueueSignalledMode::PTHREAD) + if (mode == QueueSignalledMode::PTHREAD) pthread_cond_wait(&qs->pthread.ready, &qs->pthread.mutex); - else if (qs->mode == QueueSignalledMode::POLLING) + else if (mode == QueueSignalledMode::POLLING) continue; // Try again #ifdef HAS_EVENTFD - else if (qs->mode == QueueSignalledMode::EVENTFD) { + else if (mode == QueueSignalledMode::EVENTFD) { int ret; uint64_t cntr; ret = read(qs->eventfd, &cntr, sizeof(cntr)); diff --git a/lib/sample.cpp b/lib/sample.cpp index d865f6f14..29332fb95 100644 --- a/lib/sample.cpp +++ b/lib/sample.cpp @@ -27,7 +27,7 @@ int villas::node::sample_init(struct Sample *s) { s->length = 0; s->capacity = (p->blocksz - sizeof(struct Sample)) / sizeof(s->data[0]); - s->refcnt = ATOMIC_VAR_INIT(1); + s->refcnt = 1; new (&s->signals) std::shared_ptr; @@ -43,7 +43,7 @@ struct Sample *villas::node::sample_alloc(struct Pool *p) { s->pool_off = (char *)p - (char *)s; - int ret = sample_init(s); + int const ret = sample_init(s); if (ret) { pool_put(p, s); return nullptr; @@ -53,7 +53,7 @@ struct Sample *villas::node::sample_alloc(struct Pool *p) { } struct Sample *villas::node::sample_alloc_mem(int capacity) { - size_t sz = SAMPLE_LENGTH(capacity); + size_t const sz = SAMPLE_LENGTH(capacity); auto *s = (struct Sample *)new char[sz]; if (!s) @@ -65,7 +65,7 @@ struct Sample *villas::node::sample_alloc_mem(int capacity) { s->length = 0; s->capacity = capacity; - s->refcnt = ATOMIC_VAR_INIT(1); + s->refcnt = 1; return s; } @@ -124,7 +124,7 @@ int villas::node::sample_incref(struct Sample *s) { } int villas::node::sample_decref(struct Sample *s) { - int prev = atomic_fetch_sub(&s->refcnt, 1); + int const prev = atomic_fetch_sub(&s->refcnt, 1); // Did we had the last reference? if (prev == 1) @@ -319,7 +319,7 @@ void villas::node::sample_data_remove(struct Sample *smp, size_t offset, } } - size_t sz = sizeof(smp->data[0]) * (smp->length - offset - len); + size_t const sz = sizeof(smp->data[0]) * (smp->length - offset - len); memmove(&smp->data[offset], &smp->data[offset + len], sz); diff --git a/lib/shmem.cpp b/lib/shmem.cpp index d6740ed2b..4afecf58c 100644 --- a/lib/shmem.cpp +++ b/lib/shmem.cpp @@ -93,8 +93,8 @@ int villas::node::shmem_int_open(const char *wname, const char *rname, shared->polling = conf->polling; - int flags = (int)QueueSignalledFlags::PROCESS_SHARED; - enum QueueSignalledMode mode = + int const flags = (int)QueueSignalledFlags::PROCESS_SHARED; + enum QueueSignalledMode const mode = conf->polling ? QueueSignalledMode::POLLING : QueueSignalledMode::PTHREAD; ret = queue_signalled_init(&shared->queue, conf->queuelen, manager, mode, diff --git a/lib/web.cpp b/lib/web.cpp index b3b2be629..4cae1bd43 100644 --- a/lib/web.cpp +++ b/lib/web.cpp @@ -78,6 +78,7 @@ static lws_http_mount mounts[] = { #endif // WITH_API }; +#ifndef LWS_WITHOUT_EXTENSIONS // List of libwebsockets extensions. static const lws_extension extensions[] = { #ifdef LWS_DEFLATE_FOUND @@ -89,6 +90,7 @@ static const lws_extension extensions[] = { .client_offer = "deflate_frame"}, #endif // LWS_DEFLATE_FOUND {nullptr /* terminator */}}; +#endif void Web::lwsLogger(int lws_lvl, const char *msg) { char *nl; @@ -101,7 +103,7 @@ void Web::lwsLogger(int lws_lvl, const char *msg) { if (strstr(msg, "Unable to open") == msg) lws_lvl = LLL_WARN; - Logger logger = Log::get("lws"); + Logger const logger = Log::get("lws"); switch (lws_lvl) { case LLL_ERR: diff --git a/plugins/example_hook.cpp b/plugins/example_hook.cpp index 1c56ce885..bac221e12 100644 --- a/plugins/example_hook.cpp +++ b/plugins/example_hook.cpp @@ -16,7 +16,7 @@ class ExampleHook : public Hook { public: using Hook::Hook; - virtual void restart() { + void restart() override { logger->info("The path {} restarted!", path->toString()); } }; diff --git a/src/villas-compare.cpp b/src/villas-compare.cpp index 818254a6e..dd47ab6ba 100644 --- a/src/villas-compare.cpp +++ b/src/villas-compare.cpp @@ -101,7 +101,7 @@ class Compare : public Tool { std::vector filenames; - void usage() { + void usage() override { std::cout << "Usage: villas-compare [OPTIONS] FILE1 FILE2 ... FILEn" << std::endl << " FILE a list of files to compare" << std::endl @@ -130,7 +130,7 @@ class Compare : public Tool { printCopyright(); } - void parse() { + void parse() override { // Parse Arguments int c; char *endptr; @@ -192,7 +192,7 @@ class Compare : public Tool { filenames.push_back(argv[optind + i]); } - int main() { + int main() override { int ret, rc = 0, failed; unsigned eofs; @@ -223,7 +223,7 @@ class Compare : public Tool { if (eofs) { if (eofs == sides.size()) - ret = 0; + rc = 0; else { std::cout << "length unequal" << std::endl; rc = 1; diff --git a/src/villas-conf2json.cpp b/src/villas-conf2json.cpp index ed9e5bf79..29121e249 100644 --- a/src/villas-conf2json.cpp +++ b/src/villas-conf2json.cpp @@ -6,6 +6,7 @@ */ #include +#include #include #include @@ -26,14 +27,14 @@ class Config2Json : public Tool { Config2Json(int argc, char *argv[]) : Tool(argc, argv, "conf2json") {} protected: - void usage() { + void usage() override { std::cout << "Usage: conf2json input.conf > output.json" << std::endl << std::endl; printCopyright(); } - int main() { + int main() override { int ret; config_t cfg; config_setting_t *cfg_root; @@ -44,7 +45,9 @@ class Config2Json : public Tool { exit(EXIT_FAILURE); } - FILE *f = fopen(argv[1], "r"); + auto file_destructor = [](FILE *file) { fclose(file); }; + auto f = std::unique_ptr{ + fopen(argv[1], "r"), file_destructor}; if (f == nullptr) return -1; @@ -54,7 +57,7 @@ class Config2Json : public Tool { config_set_include_dir(&cfg, confdir); - ret = config_read(&cfg, f); + ret = config_read(&cfg, f.get()); if (ret != CONFIG_TRUE) return -2; diff --git a/src/villas-convert.cpp b/src/villas-convert.cpp index 73fe656b1..494236606 100644 --- a/src/villas-convert.cpp +++ b/src/villas-convert.cpp @@ -52,7 +52,7 @@ class Convert : public Tool { Format *formatter; } dirs[2]; - void usage() { + void usage() override { std::cout << "Usage: villas-convert [OPTIONS]" << std::endl << " OPTIONS are:" << std::endl << " -i FMT set the input format" << std::endl @@ -67,7 +67,7 @@ class Convert : public Tool { printCopyright(); } - void parse() { + void parse() override { // Parse optional command line arguments int c; while ((c = getopt(argc, argv, "Vhd:i:o:t:")) != -1) { @@ -105,13 +105,13 @@ class Convert : public Tool { } } - int main() { + int main() override { int ret; for (unsigned i = 0; i < ARRAY_LEN(dirs); i++) { json_t *json_format; json_error_t err; - std::string format = dirs[i].format; + std::string const format = dirs[i].format; // Try parsing format config as JSON json_format = json_loads(format.c_str(), 0, &err); diff --git a/src/villas-graph.cpp b/src/villas-graph.cpp index 78e19c67f..7e810843d 100644 --- a/src/villas-graph.cpp +++ b/src/villas-graph.cpp @@ -56,14 +56,14 @@ class Graph : public Tool { std::string configFilename; - void usage() { + void usage() override { std::cout << "Usage: villas-graph [OPTIONS]" << std::endl << "For OPTIONS see dot(1)."; printCopyright(); } - void parse() { + void parse() override { gvParseArgs(gvc, argc, argv); std::list filenames; @@ -77,7 +77,7 @@ class Graph : public Tool { configFilename = filenames.front(); } - virtual void handler(int signal, siginfo_t *siginfp, void *) { + void handler(int signal, siginfo_t *siginfp, void *) override { #ifndef _WIN32 switch (signal) { case SIGINT: @@ -98,7 +98,7 @@ class Graph : public Tool { #endif // _WIN32 } - int main() { + int main() override { int ret; villas::node::SuperNode sn; diff --git a/src/villas-hook.cpp b/src/villas-hook.cpp index 1441242b3..61a30f7df 100644 --- a/src/villas-hook.cpp +++ b/src/villas-hook.cpp @@ -68,9 +68,11 @@ class Hook : public Tool { json_t *config; - void handler(int signal, siginfo_t *sinfo, void *ctx) { stop = true; } + void handler(int signal, siginfo_t *sinfo, void *ctx) override { + stop = true; + } - void usage() { + void usage() override { std::cout << "Usage: villas-hook [OPTIONS] NAME" << std::endl << " NAME the name of the hook function" << std::endl << " PARAM* a string of configuration settings for the hook" @@ -111,7 +113,7 @@ class Hook : public Tool { printCopyright(); } - void parse() { + void parse() override { int ret; std::string file; @@ -188,7 +190,7 @@ class Hook : public Tool { hook = argv[optind]; } - int main() { + int main() override { int ret, recv, sent; struct Sample *smps[cnt]; @@ -245,7 +247,7 @@ class Hook : public Tool { if (recv < 0) throw RuntimeError("Failed to read from stdin"); - timespec now = time_now(); + timespec const now = time_now(); logger->debug("Read {} smps from stdin", recv); diff --git a/src/villas-node.cpp b/src/villas-node.cpp index 190e2e7e3..cb4ecb45b 100644 --- a/src/villas-node.cpp +++ b/src/villas-node.cpp @@ -51,7 +51,7 @@ class Node : public Tool { std::string uri; bool showCapabilities = false; - void handler(int signal, siginfo_t *sinfo, void *ctx) { + void handler(int signal, siginfo_t *sinfo, void *ctx) override { switch (signal) { case SIGALRM: logger->info("Reached timeout. Terminating..."); @@ -64,7 +64,7 @@ class Node : public Tool { sn.setState(State::STOPPING); } - void usage() { + void usage() override { std::cout << "Usage: villas-node [OPTIONS] [CONFIG]" << std::endl << " OPTIONS is one or more of the following options:" << std::endl @@ -119,7 +119,7 @@ class Node : public Tool { printCopyright(); } - void parse() { + void parse() override { // Parse optional command line arguments int c; while ((c = getopt(argc, argv, "hCVd:")) != -1) { @@ -153,7 +153,7 @@ class Node : public Tool { } } - int main() { return showCapabilities ? capabilities() : daemon(); } + int main() override { return showCapabilities ? capabilities() : daemon(); } int capabilities() { auto *json_caps = getCapabilities(); diff --git a/src/villas-pipe.cpp b/src/villas-pipe.cpp index 8febf76a8..0757dbb60 100644 --- a/src/villas-pipe.cpp +++ b/src/villas-pipe.cpp @@ -60,16 +60,17 @@ class PipeDirection { logger = Log::get(loggerName); // Initialize memory - unsigned pool_size = + unsigned const pool_size = LOG2_CEIL(MAX(node->out.vectorize, node->in.vectorize)); - int ret = pool_init(&pool, pool_size, SAMPLE_LENGTH(DEFAULT_SAMPLE_LENGTH), - node->getMemoryType()); + int const ret = + pool_init(&pool, pool_size, SAMPLE_LENGTH(DEFAULT_SAMPLE_LENGTH), + node->getMemoryType()); if (ret < 0) throw RuntimeError("Failed to allocate memory for pool."); } - ~PipeDirection() { + virtual ~PipeDirection() { int ret __attribute__((unused)); ret = pool_destroy(&pool); @@ -103,7 +104,7 @@ class PipeSendDirection : public PipeDirection { PipeSendDirection(Node *n, Format *i, bool en = true, int lim = -1) : PipeDirection(n, i, en, lim, "send") {} - virtual void run() { + void run() override { logger->debug("Send thread started"); unsigned last_sequenceno = 0; @@ -169,7 +170,7 @@ class PipeReceiveDirection : public PipeDirection { PipeReceiveDirection(Node *n, Format *i, bool en = true, int lim = -1) : PipeDirection(n, i, en, lim, "recv") {} - virtual void run() { + void run() override { logger->debug("Receive thread started"); int recv, allocated = 0; @@ -230,7 +231,7 @@ class Pipe : public Tool { recv.enabled = true; recv.limit = -1; - int ret = memory::init(DEFAULT_NR_HUGEPAGES); + int const ret = memory::init(DEFAULT_NR_HUGEPAGES); if (ret) throw RuntimeError("Failed to initialize memory"); } @@ -265,7 +266,7 @@ class Pipe : public Tool { std::unique_ptr dir; } send; - void handler(int signal, siginfo_t *sinfo, void *ctx) { + void handler(int signal, siginfo_t *sinfo, void *ctx) override { logger->debug("Received {} signal.", strsignal(signal)); switch (signal) { @@ -295,7 +296,7 @@ class Pipe : public Tool { } } - void usage() { + void usage() override { std::cout << "Usage: villas-pipe [OPTIONS] CONFIG NODE" << std::endl << " CONFIG path to a configuration file" << std::endl @@ -324,7 +325,7 @@ class Pipe : public Tool { printCopyright(); } - void parse() { + void parse() override { int c, ret; char *endptr; while ((c = getopt(argc, argv, "Vhxrsd:l:L:T:f:t:o:")) != -1) { @@ -398,7 +399,7 @@ class Pipe : public Tool { nodestr = argv[optind + 1]; } - int main() { + int main() override { int ret; Node *node; json_t *json_format; diff --git a/src/villas-relay.cpp b/src/villas-relay.cpp index f02313024..2b13c80e2 100644 --- a/src/villas-relay.cpp +++ b/src/villas-relay.cpp @@ -137,7 +137,7 @@ void RelayConnection::write() { auto fr = outgoingFrames.front(); - int ret = lws_write(wsi, fr->data(), fr->size(), LWS_WRITE_BINARY); + int const ret = lws_write(wsi, fr->data(), fr->size(), LWS_WRITE_BINARY); if (ret < 0) return; diff --git a/src/villas-relay.hpp b/src/villas-relay.hpp index 1c62f244e..ce7ba5853 100644 --- a/src/villas-relay.hpp +++ b/src/villas-relay.hpp @@ -142,13 +142,15 @@ class Relay : public Tool { static int protocolCallback(lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len); - void usage(); + void usage() override; - void parse(); + void parse() override; - int main(); + int main() override; - void handler(int signal, siginfo_t *sinfo, void *ctx) { stop = true; } + void handler(int signal, siginfo_t *sinfo, void *ctx) override { + stop = true; + } }; } // namespace tools diff --git a/src/villas-signal.cpp b/src/villas-signal.cpp index 9a5de77a0..664f9357c 100644 --- a/src/villas-signal.cpp +++ b/src/villas-signal.cpp @@ -53,7 +53,7 @@ class Signal : public Tool { std::string format; - void usage() { + void usage() override { std::cout << "Usage: villas-signal [OPTIONS] SIGNAL" << std::endl << " SIGNAL is on of the following signal types:" << std::endl @@ -191,7 +191,7 @@ class Signal : public Tool { for (int i = 0; i < values; i++) { json_t *json_signal = json_pack( "{ s: s, s: f, s: f, s: f, s: f, s: f, s: f, s: f, s: f }", "signal", - strdup(type.c_str()), "frequency", frequency, "amplitude", amplitude, + type.c_str(), "frequency", frequency, "amplitude", amplitude, "stddev", stddev, "offset", offset, "pulse_width", pulse_width, "pulse_low", pulse_low, "pulse_high", pulse_high, "phase", phase); @@ -203,7 +203,7 @@ class Signal : public Tool { "in", "signals", json_signals); } - void handler(int signal, siginfo_t *sinfo, void *ctx) { + void handler(int signal, siginfo_t *sinfo, void *ctx) override { switch (signal) { case SIGALRM: logger->info("Reached timeout. Terminating..."); @@ -216,7 +216,7 @@ class Signal : public Tool { stop = true; } - int main() { + int main() override { int ret; json_t *json, *json_format; json_error_t err; diff --git a/src/villas-test-config.cpp b/src/villas-test-config.cpp index b482d67ce..5b0dc8557 100644 --- a/src/villas-test-config.cpp +++ b/src/villas-test-config.cpp @@ -42,7 +42,7 @@ class TestConfig : public Tool { bool check; bool dump; - void usage() { + void usage() override { std::cout << "Usage: villas-test-config [OPTIONS] CONFIG" << std::endl << " CONFIG is the path to an optional configuration file" << std::endl @@ -59,7 +59,7 @@ class TestConfig : public Tool { printCopyright(); } - void parse() { + void parse() override { int c; while ((c = getopt(argc, argv, "hcVD")) != -1) { switch (c) { @@ -90,7 +90,7 @@ class TestConfig : public Tool { uri = argv[optind]; } - int main() { + int main() override { SuperNode sn; sn.parse(uri); diff --git a/src/villas-zmq-keygen.cpp b/src/villas-zmq-keygen.cpp index 507840588..1aa7e281d 100644 --- a/src/villas-zmq-keygen.cpp +++ b/src/villas-zmq-keygen.cpp @@ -26,7 +26,7 @@ class ZmqKeygen : public Tool { ZmqKeygen(int argc, char *argv[]) : Tool(argc, argv, "zmq-keygen") {} protected: - int main() { + int main() override { int ret; char public_key[41]; char secret_key[41]; diff --git a/tests/unit/config.cpp b/tests/unit/config.cpp index 4e1b12bc4..94acac715 100644 --- a/tests/unit/config.cpp +++ b/tests/unit/config.cpp @@ -7,6 +7,7 @@ #include #include +#include #include @@ -19,16 +20,18 @@ using namespace villas::node; Test(config, env) { const char *cfg_f = "test = \"${MY_ENV_VAR}\"\n"; - std::FILE *f = std::tmpfile(); - std::fputs(cfg_f, f); - std::rewind(f); + auto file_destructor = [](FILE *file) { std::fclose(file); }; + auto f = std::unique_ptr{std::tmpfile(), + file_destructor}; + cr_assert(f); - auto c = Config(); + std::fputs(cfg_f, f.get()); + std::rewind(f.get()); - char env[] = "MY_ENV_VAR=mobydick"; - putenv(env); + auto c = Config(); + setenv("MY_ENV_VAR", "mobydick", true); - auto *r = c.load(f); + auto *r = c.load(f.get()); cr_assert_not_null(r); auto *j = json_object_get(r, "test"); @@ -42,9 +45,10 @@ Test(config, include) { const char *cfg_f2 = "magic = 1234\n"; char f2_fn_tpl[] = "/tmp/villas.unit-test.XXXXXX"; - int f2_fd = mkstemp(f2_fn_tpl); + int const f2_fd = mkstemp(f2_fn_tpl); std::FILE *f2 = fdopen(f2_fd, "w"); + cr_assert(f2); std::fputs(cfg_f2, f2); std::rewind(f2); @@ -54,8 +58,8 @@ Test(config, include) { std::fputs(cfg_f1.c_str(), f1); std::rewind(f1); - auto env = fmt::format("INCLUDE_FILE={}", f2_fn_tpl).c_str(); - putenv((char *)env); + auto env = fmt::format("INCLUDE_FILE={}", f2_fn_tpl); + putenv(env.data()); auto c = Config(); diff --git a/tests/unit/format.cpp b/tests/unit/format.cpp index 020399bf1..0c78a2531 100644 --- a/tests/unit/format.cpp +++ b/tests/unit/format.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include @@ -20,8 +20,6 @@ #include #include -#include "helpers.hpp" - using namespace villas; using namespace villas::node; @@ -117,8 +115,9 @@ void cr_assert_eq_sample(struct Sample *a, struct Sample *b, int flags) { case SignalType::INTEGER: cr_assert_eq(a->data[j].i, b->data[j].i, - "Sample data mismatch at index %d: %lld != %lld", j, - a->data[j].i, b->data[j].i); + "Sample data mismatch at index %d: %" PRId64 + " != %" PRId64, + j, a->data[j].i, b->data[j].i); break; case SignalType::BOOLEAN: @@ -171,8 +170,9 @@ void cr_assert_eq_sample_raw(struct Sample *a, struct Sample *b, int flags, case SignalType::INTEGER: cr_assert_eq(a->data[j].i, b->data[j].i, - "Sample data mismatch at index %d: %lld != %lld", j, - a->data[j].i, b->data[j].i); + "Sample data mismatch at index %d: %" PRId64 + " != %" PRId64, + j, a->data[j].i, b->data[j].i); break; case SignalType::BOOLEAN: @@ -240,7 +240,7 @@ ParameterizedTest(Param *p, format, lowlevel, .init = init_memory) { char buf[8192]; size_t wbytes, rbytes; - Logger logger = Log::get("test:format:lowlevel"); + Logger const logger = Log::get("test:format:lowlevel"); logger->info("Running test for format={}, cnt={}", p->fmt, p->cnt); @@ -330,7 +330,7 @@ ParameterizedTest(Param *p, format, highlevel, .init = init_memory) { int ret, cnt; char *retp; - Logger logger = Log::get("test:format:highlevel"); + Logger const logger = Log::get("test:format:highlevel"); logger->info("Running test for format={}, cnt={}", p->fmt, p->cnt); @@ -391,6 +391,7 @@ ParameterizedTest(Param *p, format, highlevel, .init = init_memory) { #endif rewind(stream); + (void)errno; // TODO: should we handle rewind errors? cnt = fmt->scan(stream, smpt, p->cnt); cr_assert_eq(cnt, p->cnt, "Read only %d of %d samples back", cnt, p->cnt); diff --git a/tests/unit/queue.cpp b/tests/unit/queue.cpp index ddc3c2ce6..c575584e3 100644 --- a/tests/unit/queue.cpp +++ b/tests/unit/queue.cpp @@ -76,7 +76,7 @@ static void *producer(void *ctx) { struct param *p = (struct param *)ctx; srand((unsigned)time(0) + thread_get_id()); - size_t nops = rand() % 1000; + size_t const nops = rand() % 1000; // Wait for global start signal while (p->start == 0) @@ -102,7 +102,7 @@ static void *consumer(void *ctx) { struct param *p = (struct param *)ctx; srand((unsigned)time(0) + thread_get_id()); - size_t nops = rand() % 1000; + size_t const nops = rand() % 1000; // Wait for global start signal while (p->start == 0) @@ -133,7 +133,7 @@ void *producer_consumer(void *ctx) { struct param *p = (struct param *)ctx; srand((unsigned)time(0) + thread_get_id()); - size_t nops = rand() % 1000; + size_t const nops = rand() % 1000; // Wait for global start signal while (p->start == 0) @@ -166,7 +166,7 @@ void *producer_consumer_many(void *ctx) { struct param *p = (struct param *)ctx; srand((unsigned)time(0) + thread_get_id()); - size_t nops = rand() % 1000; + size_t const nops = rand() % 1000; // Wait for global start signal while (p->start == 0) @@ -269,7 +269,7 @@ ParameterizedTest(struct param *p, queue, multi_threaded, .timeout = 20, int ret, cycpop; struct Tsc tsc; - Logger logger = Log::get("test:queue:multi_threaded"); + Logger const logger = Log::get("test:queue:multi_threaded"); if (!utils::isPrivileged() && p->mt == &memory::mmap_hugetlb) cr_skip_test("Skipping memory_mmap_hugetlb tests allocatpr because we are " @@ -290,7 +290,7 @@ ParameterizedTest(struct param *p, queue, multi_threaded, .timeout = 20, pthread_create(&threads[i], nullptr, p->many ? producer_consumer_many : producer_consumer, p); - sleep(0.2); + // sleep(0.2); TODO: Is this supposed to to something? Yield? ret = tsc_init(&tsc); cr_assert(!ret); From f67eb09dbf5dc79aac55c57bfe4494b464b40f7f Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Wed, 4 Jun 2025 15:19:30 +0200 Subject: [PATCH 4/6] nix: Add clang-built package and devShell Signed-off-by: Philipp Jungkamp --- flake.nix | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/flake.nix b/flake.nix index 330032da9..53a8d8769 100644 --- a/flake.nix +++ b/flake.nix @@ -73,6 +73,10 @@ withAllNodes = true; }; + villas-node-clang = pkgs.villas-node.override { + stdenv = pkgs.clangStdenv; + }; + dockerImage = pkgs.dockerTools.buildLayeredImage { name = "villas-node"; tag = "latest-nix"; @@ -81,7 +85,6 @@ }; # Cross-compiled packages - villas-node-x86_64-linux = if pkgs.system == "x86_64-linux" then pkgs.villas-node else pkgs.pkgsCross.x86_64-linux.villas-node; villas-node-aarch64-linux = if pkgs.system == "aarch64-linux" then pkgs.villas-node else pkgs.pkgsCross.aarch64-multiplatform.villas-node; @@ -126,7 +129,7 @@ system: let pkgs = devPkgsFor system; - hardeningDisable = [ "all" ]; + packages = with pkgs; [ bashInteractive bc @@ -142,19 +145,35 @@ pre-commit ruby # for pre-commit markdownlint hook ]; + + mkShellFor = stdenv: pkg: stdenv.mkDerivation { + name = "${pkg.pname}-${stdenv.cc.cc.pname}-devShell"; + + # disable all hardening to suppress warnings in debug builds + hardeningDisable = [ "all" ]; + + # inherit inputs from pkg + buildInputs = pkg.buildInputs ++ packages; + nativeBuildInputs = pkg.nativeBuildInputs ++ packages; + propagatedBuildInputs = pkg.propagatedBuildInputs; + propagatedNativeBuildInputs = pkg.propagatedNativeBuildInputs; + + # configure nix-ld for pre-commit + env = { + NIX_LD = lib.fileContents "${stdenv.cc}/nix-support/dynamic-linker"; + NIX_LD_LIBRARY_PATH = lib.makeLibraryPath [ pkgs.gcc-unwrapped.lib ]; + }; + }; in rec { - default = full; + default = gcc; - full = pkgs.mkShell { - inherit hardeningDisable packages; - name = "full"; - inputsFrom = with pkgs; [ villas-node ]; - }; + gcc = mkShellFor pkgs.stdenv pkgs.villas-node; + clang = mkShellFor pkgs.clangStdenv pkgs.villas-node; python = pkgs.mkShell { - inherit hardeningDisable; - name = "python"; + name = "villas-python-devShell"; + hardeningDisable = [ "all" ]; inputsFrom = with pkgs; [ villas-node-python ]; packages = with pkgs; From 10f83c33ce53c1e235d200d3012e22746d570ae0 Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Wed, 4 Jun 2025 15:20:07 +0200 Subject: [PATCH 5/6] tools: Use git ls-files instead of find Signed-off-by: Philipp Jungkamp --- tools/format-all.sh | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/tools/format-all.sh b/tools/format-all.sh index f5d73eb93..0d90f377f 100755 --- a/tools/format-all.sh +++ b/tools/format-all.sh @@ -6,8 +6,5 @@ # SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University # SPDX-License-Identifier: Apache-2.0 -TOP_DIR=$(git rev-parse --show-toplevel) - -find ${TOP_DIR} \( -iname "*.cpp" -o -iname "*.hpp" -o -iname "*.h" -o -iname "*.c" \) -a \ - -not \( -path "${TOP_DIR}/fpga/thirdparty/*" -o -path "${TOP_DIR}/build*/*" \) | \ - xargs clang-format --verbose -i +git ls-files -c -z -- "*.c" ".h" "*.hpp" "*.cpp" ":!:fpga/thirdparty" |\ + xargs -0 clang-format --verbose -i From 3f9dfc6b52227e26d6247cc87ab5c8c8ab0fdb72 Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Wed, 4 Jun 2025 15:27:22 +0200 Subject: [PATCH 6/6] nix: Install pre-commit hooks using direnv Signed-off-by: Philipp Jungkamp --- .envrc | 1 + 1 file changed, 1 insertion(+) diff --git a/.envrc b/.envrc index 6dff70de7..585a87ee8 100644 --- a/.envrc +++ b/.envrc @@ -2,3 +2,4 @@ # SPDX-License-Identifier: Apache-2.0 use flake +pre-commit install