~aleteoryx/muditaos

93c4675d1da115c9995368886884cf69a1c5e490 — Alek Rudnik 4 years ago c1bb6c1
[EGD-6701] System time usage fixes

Fixed all calls to stdlib time.
Removed all redundant calls to Timestamp treated as time source.
M board/rt1051/crashdump/crashdumpwriter_vfs.hpp => board/rt1051/crashdump/crashdumpwriter_vfs.hpp +1 -1
@@ 33,7 33,7 @@ namespace crashdump
        {
            std::time_t now;
            std::time(&now);
            std::strftime(name.data(), name.size(), CrashDumpFileNameFormat, gmtime(&now));
            std::strftime(name.data(), name.size(), CrashDumpFileNameFormat, std::localtime(&now));
        }

        int dumpFd{-1};

M board/rt1051/memwrap.c => board/rt1051/memwrap.c +0 -9
@@ 58,13 58,6 @@ void* calloc (size_t num, size_t size)
    return memset(p, 0, total);
}

/* struct tm * localtime(const time_t *t)
{
  static struct tm y = {0};
  //RtcServiceGetCurrentDateTime(&tm);
  return &y;
} */

void *realloc(void *aptr, size_t nbytes)
{
    return userrealloc(aptr, nbytes);


@@ 104,5 97,3 @@ void _putchar(char character)
{
    // Use of printf is banned
}



M module-apps/application-calendar/ApplicationCalendar.cpp => module-apps/application-calendar/ApplicationCalendar.cpp +2 -3
@@ 20,7 20,7 @@
#include <service-db/QueryMessage.hpp>
#include <service-db/DBNotificationMessage.hpp>

#include <time/time_conversion.hpp>
#include <ctime>

namespace app
{


@@ 98,8 98,7 @@ namespace app

    sys::ReturnCodes ApplicationCalendar::InitHandler()
    {
        utils::time::Timestamp timestamp;
        applicationStartTime = timestamp.getTime();
        applicationStartTime = std::time(nullptr);
        auto ret             = Application::InitHandler();
        createUserInterface();
        return ret;

M module-apps/application-calendar/data/dateCommon.hpp => module-apps/application-calendar/data/dateCommon.hpp +3 -4
@@ 103,8 103,7 @@ inline time_t TimePointToTimeT(const TimePoint &tp)

inline TimePoint TimePointNow()
{
    utils::time::Timestamp timestamp;
    return TimePointFromTimeT(timestamp.getTime());
    return TimePointFromTimeT(std::time(nullptr));
}

inline std::string TimePointToString(const TimePoint &tp)


@@ 130,7 129,7 @@ inline auto LocalizedHoursToUtcHours(int hour = 0)
{
    std::tm tm           = CreateTmStruct(unix_epoch_year, 1, 1, hour, 0, 0);
    std::time_t basetime = std::mktime(&tm);
    basetime -= utils::time::Time::getTimeZoneOffset();
    basetime -= GetDiffLocalWithUTCTime();
    return TimePointToHour24H(TimePointFromTimeT(basetime));
}



@@ 304,7 303,7 @@ inline std::string createUID()
{
    constexpr uint32_t bufferLimit = 16;
    char Buffer[bufferLimit];
    utils::time::Timestamp timestamp;
    utils::time::Timestamp timestamp = utils::time::getCurrentTimestamp();
    std::string UID{timestamp.str("%Y%m%dT%H%M%S")};
    UID += '-';
    std::random_device rd;

M module-apps/application-call/ApplicationCall.cpp => module-apps/application-call/ApplicationCall.cpp +0 -3
@@ 91,9 91,6 @@ namespace app
        return getState() == call::State::IDLE;
    }

    //  number of seconds after end call to switch back to previous application
    const inline utils::time::Duration delayToSwitchToPreviousApp = 3;

    void ApplicationCall::CallAbortHandler()
    {
        manager::Controller::sendAction(this, manager::actions::Call, std::make_unique<app::CallAbortData>());

M module-apps/application-desktop/windows/DesktopMainWindow.cpp => module-apps/application-desktop/windows/DesktopMainWindow.cpp +1 -1
@@ 230,7 230,7 @@ namespace gui
    {
        using namespace utils::time;
        auto ret       = AppWindow::updateTime();
        auto timestamp = utils::time::Timestamp();
        auto timestamp = utils::time::getCurrentTimestamp();
        if (time != nullptr) {
            auto fmt = utils::dateAndTimeSettings.isTimeFormat12()
                           ? Locale::format(Locale::TimeFormat::FormatTime12HShort)

M module-apps/application-messages/ApplicationMessages.cpp => module-apps/application-messages/ApplicationMessages.cpp +7 -8
@@ 32,10 32,10 @@
#include <module-db/queries/phonebook/QueryContactGetByID.hpp>

#include <service-cellular/CellularMessage.hpp>
#include <messages/OptionsWindow.hpp>

#include <cassert>
#include <time/time_conversion.hpp>
#include <messages/OptionsWindow.hpp>
#include <ctime>

namespace app
{


@@ 329,7 329,7 @@ namespace app
        assert(!body.empty()); // precondition check.

        record.body = body;
        record.date = utils::time::getCurrentTimestamp().getTime();
        record.date = std::time(nullptr);

        using db::query::SMSUpdate;
        const auto [succeed, _] =


@@ 346,7 346,7 @@ namespace app
        record.number = number;
        record.body   = body;
        record.type   = SMSType::DRAFT;
        record.date   = utils::time::getCurrentTimestamp().getTime();
        record.date   = std::time(nullptr);

        using db::query::SMSAdd;
        const auto [success, _] =


@@ 372,7 372,7 @@ namespace app
        record.number = number;
        record.body   = body;
        record.type   = SMSType::QUEUED;
        record.date   = utils::time::getCurrentTimestamp().getTime();
        record.date   = std::time(nullptr);

        using db::query::SMSAdd;
        const auto [succeed, _] =


@@ 384,9 384,8 @@ namespace app
    {
        auto resendRecord = record;
        resendRecord.type = SMSType::QUEUED;
        resendRecord.date =
            utils::time::getCurrentTimestamp().getTime(); // update date sent - it will display an old, failed sms at
                                                          // the the bottom, but this is correct
        resendRecord.date = std::time(nullptr); // update date sent - it will display an old, failed sms at
                                                // the the bottom, but this is correct

        using db::query::SMSUpdate;
        const auto [succeed, _] =

M module-apps/application-notes/windows/NoteEditWindow.cpp => module-apps/application-notes/windows/NoteEditWindow.cpp +3 -2
@@ 14,11 14,12 @@
#include <module-apps/messages/OptionsWindow.hpp>

#include <i18n/i18n.hpp>
#include <module-utils/time/time_conversion.hpp>

#include <module-gui/gui/widgets/BottomBar.hpp>
#include <module-gui/gui/widgets/TopBar.hpp>

#include <ctime>

namespace app::notes
{
    namespace


@@ 138,7 139,7 @@ namespace app::notes

    void NoteEditWindow::saveNote()
    {
        notesRecord->date    = utils::time::getCurrentTimestamp().getTime();
        notesRecord->date    = std::time(nullptr);
        notesRecord->snippet = edit->getText();
        presenter->save(*notesRecord);
    }

M module-apps/application-settings/windows/DateTimeWindow.cpp => module-apps/application-settings/windows/DateTimeWindow.cpp +1 -1
@@ 58,7 58,7 @@ namespace gui
        // create date widgets
        uint32_t w = this->getWidth();

        utils::time::Timestamp time;
        utils::time::Timestamp time = utils::time::getCurrentTimestamp();

        // create date widgets
        dateBody = new gui::HBox(this,

M module-apps/popups/lock-popups/PhoneLockedWindow.cpp => module-apps/popups/lock-popups/PhoneLockedWindow.cpp +1 -1
@@ 147,7 147,7 @@ namespace gui
    {
        using namespace utils::time;
        auto ret       = AppWindow::updateTime();
        auto timestamp = utils::time::Timestamp();
        auto timestamp = utils::time::getCurrentTimestamp();
        if (time != nullptr) {
            auto fmt = utils::dateAndTimeSettings.isTimeFormat12()
                           ? Locale::format(Locale::TimeFormat::FormatTime12HShort)

M module-audio/Audio/Operation/RecorderOperation.cpp => module-audio/Audio/Operation/RecorderOperation.cpp +0 -2
@@ 21,8 21,6 @@ namespace audio

#define PERF_STATS_ON 0

    using namespace bsp;

    RecorderOperation::RecorderOperation(const char *file, AudioServiceMessage::Callback callback) : Operation(callback)
    {


M module-cellular/modem/mux/CellularMux.cpp => module-cellular/modem/mux/CellularMux.cpp +3 -1
@@ 14,11 14,13 @@
#include <service-cellular/CellularMessage.hpp>

#include <RTOSWrapper/include/ticks.hpp>
#include <SystemManager/messages/DeviceRegistrationMessage.hpp>
#include <time/time_conversion.hpp>

#include <gsl/gsl_util>

#include <memory>
#include <sstream>
#include <SystemManager/messages/DeviceRegistrationMessage.hpp>

std::map<TypeOfFrame_e, std::string> TypeOfFrame_text = {{TypeOfFrame_e::SABM, "SABM"},
                                                         {TypeOfFrame_e::UA, "UA"},

M module-gui/gui/widgets/TopBar/Time.cpp => module-gui/gui/widgets/TopBar/Time.cpp +2 -2
@@ 2,9 2,9 @@
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "Time.hpp"
#include "time/time_conversion.hpp"
#include "Style.hpp"

#include <ctime>
namespace gui::top_bar
{
    Time::Time(Item *parent, uint32_t x, uint32_t y, uint32_t w, uint32_t h)


@@ 21,7 21,7 @@ namespace gui::top_bar

    void Time::update()
    {
        _time.set_time(utils::time::getCurrentTimestamp().getTime());
        _time.set_time(std::time(nullptr));
        setText(_time.str());
    }


M module-services/service-cellular/CellularCall.cpp => module-services/service-cellular/CellularCall.cpp +4 -4
@@ 7,9 7,9 @@
#include <PhoneNumber.hpp>
#include <Utils.hpp>
#include <log/log.hpp>
#include <time/time_conversion.hpp>

#include <cinttypes>
#include <ctime>
#include <optional>
#include <sstream>
#include <stdexcept>


@@ 32,7 32,7 @@ namespace CellularCall
        clear();
        CalllogRecord callRec;
        callRec.type        = type;
        callRec.date        = utils::time::Timestamp().getTime();
        callRec.date         = std::time(nullptr);
        callRec.presentation = PresentationType::PR_UNKNOWN;
        callRec.phoneNumber  = number;
        call                = startCallAction ? startCallAction(callRec) : CalllogRecord();


@@ 51,7 51,7 @@ namespace CellularCall
    bool CellularCall::setActive()
    {
        if (isValid()) {
            startActiveTime = utils::time::Timestamp();
            startActiveTime = utils::time::getCurrentTimestamp();
            isActiveCall    = true;
            return true;
        }


@@ 70,7 70,7 @@ namespace CellularCall
        }

        if (isActiveCall) {
            auto endTime  = utils::time::Timestamp();
            auto endTime  = utils::time::getCurrentTimestamp();
            call.duration = (endTime - startActiveTime).get();
        }
        else {

M module-services/service-cellular/ServiceCellular.cpp => module-services/service-cellular/ServiceCellular.cpp +3 -3
@@ 74,7 74,6 @@
#include <service-desktop/DeveloperModeMessage.hpp>
#include <service-appmgr/model/ApplicationManager.hpp>
#include <task.h>
#include <time/time_conversion.hpp>
#include <ucs2/UCS2.hpp>
#include <utf8/UTF8.hpp>



@@ 99,6 98,8 @@
#include <service-cellular/api/request/sim.hpp>
#include <service-cellular/api/notification/notification.hpp>

#include <ctime>

const char *ServiceCellular::serviceName = cellular::service::name;

inline constexpr auto cellularStack = 8000;


@@ 1116,8 1117,7 @@ auto ServiceCellular::receiveSMS(std::string messageNumber) -> bool
                // parse date
                tokens[3].erase(std::remove(tokens[3].begin(), tokens[3].end(), '\"'), tokens[3].end());

                utils::time::Timestamp time;
                auto messageDate = time.getTime();
                auto messageDate = std::time(nullptr);

                if (tokens.size() == 5) {
                    LOG_DEBUG("Single message");

M module-services/service-desktop/ServiceDesktop.cpp => module-services/service-desktop/ServiceDesktop.cpp +5 -3
@@ 22,8 22,6 @@
#include <module-sys/SystemManager/SystemManager.hpp>
#include <module-sys/Timers/TimerFactory.hpp>

#include <cinttypes>
#include <filesystem>
#include <module-services/service-appmgr/service-appmgr/model/ApplicationManager.hpp>
#include <module-services/service-db/agents/settings/SystemSettings.hpp>
#include <module-sys/SystemManager/Constants.hpp>


@@ 34,6 32,10 @@
#include <sys/mount.h>
#include <sys/statvfs.h>

#include <ctime>
#include <cinttypes>
#include <filesystem>

namespace
{
    bool RemountFS(bool readOnly = false, std::string path = std::string(purefs::dir::getRootDiskPath()))


@@ 348,7 350,7 @@ void ServiceDesktop::storeHistory(const std::string &historyValue)
void ServiceDesktop::prepareBackupData()
{
    backupRestoreStatus.operation = ServiceDesktop::Operation::Backup;
    backupRestoreStatus.task      = std::to_string(static_cast<uint32_t>(utils::time::getCurrentTimestamp().getTime()));
    backupRestoreStatus.task          = std::to_string(static_cast<uint32_t>(std::time(nullptr)));
    backupRestoreStatus.state     = OperationState::Stopped;
    backupRestoreStatus.backupTempDir = purefs::dir::getTemporaryPath() / backupRestoreStatus.task;
}

M module-services/service-desktop/endpoints/developerMode/DeveloperModeHelper.cpp => module-services/service-desktop/endpoints/developerMode/DeveloperModeHelper.cpp +3 -2
@@ 21,11 21,12 @@
#include <module-sys/SystemManager/Constants.hpp>

#include <service-db/DBServiceAPI.hpp>
#include <time/time_conversion.hpp>
#include <service-desktop/parser/MessageHandler.hpp>
#include <service-desktop/endpoints/developerMode/event/ATRequest.hpp>
#include <service-appmgr/service-appmgr/Controller.hpp>

#include <ctime>

namespace parserFSM
{
    class Context;


@@ 283,7 284,7 @@ auto DeveloperModeHelper::smsRecordFromJson(json11::Json msgJson) -> SMSRecord
    record.type = static_cast<SMSType>(msgJson[json::messages::messageType].int_value());
    utils::PhoneNumber phoneNumber(msgJson[json::messages::phoneNumber].string_value());
    record.number = phoneNumber.getView();
    record.date   = utils::time::getCurrentTimestamp().getTime();
    record.date   = std::time(nullptr);
    record.body   = UTF8(msgJson[json::messages::messageBody].string_value());
    return record;
}

M module-services/service-desktop/endpoints/deviceInfo/DeviceInfoEndpoint.cpp => module-services/service-desktop/endpoints/deviceInfo/DeviceInfoEndpoint.cpp +3 -2
@@ 9,7 9,6 @@
#include <common_data/EventStore.hpp>
#include <json/json11.hpp>
#include <source/version.hpp>
#include <time/time_conversion.hpp>
#include <service-desktop/service-desktop/ServiceDesktop.hpp>
#include <version.hpp>



@@ 18,6 17,8 @@
#include <sys/statvfs.h>
#include <purefs/filesystem_paths.hpp>

#include <ctime>

using namespace parserFSM;

auto DeviceInfoEndpoint::handle(Context &context) -> void


@@ 61,7 62,7 @@ auto DeviceInfoEndpoint::getDeviceInfo(Context &context) -> bool
         {json::gitTag, (std::string)GIT_TAG},
         {json::gitBranch, (std::string)GIT_BRANCH},
         {json::updateHistory, updateHistory},
         {json::currentRTCTime, std::to_string(static_cast<uint32_t>(utils::time::getCurrentTimestamp().getTime()))},
         {json::currentRTCTime, std::to_string(static_cast<uint32_t>(std::time(nullptr)))},
         {json::version, std::string(VERSION)}}));

    MessageHandler::putToSendQueue(context.createSimpleResponse());

M module-services/service-desktop/endpoints/update/UpdateMuditaOS.cpp => module-services/service-desktop/endpoints/update/UpdateMuditaOS.cpp +4 -4
@@ 11,7 11,6 @@
#include <application-desktop/Constants.hpp>
#include <service-db/service-db/Settings.hpp>
#include <purefs/filesystem_paths.hpp>
#include <time/time_conversion.hpp>
#include <filesystem>
#include <Utils.hpp>
#include <boot/bootconfig.hpp>


@@ 26,8 25,9 @@
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <ctime>
#include <fstream>
#include <memory>

FileInfo::FileInfo(mtar_header_t &h, unsigned long crc32) : fileSize(h.size), fileCRC32(crc32)
{


@@ 93,7 93,7 @@ updateos::UpdateError UpdateMuditaOS::runUpdate()
{
    informDebug("Preparing temp dir");

    updateRunStatus.startTime   = utils::time::getCurrentTimestamp().getTime();
    updateRunStatus.startTime   = static_cast<uint32_t>(std::time(nullptr));
    updateRunStatus.fromVersion = bootConfig.to_json()[boot::json::git_info];
    versionInformation          = UpdateMuditaOS::getVersionInfoFromFile(updateFile);



@@ 166,7 166,7 @@ updateos::UpdateError UpdateMuditaOS::runUpdate()
        informError(err, "runUpdate cleanupAfterUpdate failed, resetting anyway");
    }

    updateRunStatus.endTime = utils::time::Time().getTime();
    updateRunStatus.endTime = static_cast<uint32_t>(std::time(nullptr));
    storeRunStatusInDB();

    // reboot always

M module-services/service-evtmgr/EventManager.cpp => module-services/service-evtmgr/EventManager.cpp +1 -1
@@ 431,4 431,4 @@ void EventManager::processTimezoneRequest(const std::string &timezone)
    }
    auto notification = std::make_shared<sys::DataMessage>(MessageType::EVMTimeUpdated);
    bus.sendMulticast(std::move(notification), sys::BusChannel::ServiceEvtmgrNotifications);
}
\ No newline at end of file
}

M module-utils/Utils.cpp => module-utils/Utils.cpp +5 -2
@@ 2,9 2,12 @@
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "Utils.hpp"
#include <filesystem>

#include <crc32.h>

#include <ctime>
#include <filesystem>

namespace utils::filesystem
{
    namespace


@@ 35,7 38,7 @@ namespace utils::filesystem

        std::random_device random_device;
        std::mt19937 generator(random_device());
        generator.seed(utils::time::Timestamp().getTime());
        generator.seed(std::time(nullptr));
        std::uniform_int_distribution<> distribution(0, CHARACTERS.size() - 1);

        std::string random_string;

M module-utils/Utils.hpp => module-utils/Utils.hpp +5 -4
@@ 3,16 3,17 @@

#pragma once
#include "Split.hpp"
#include "i18n/i18n.hpp"
#include <i18n/i18n.hpp>
#include <log/log.hpp>

#include <magic_enum.hpp>

#include <algorithm> // std::find_if_not
#include <sstream>
#include <iomanip>
#include <cmath>
#include <chrono>
#include <random>
#include "time/time_conversion.hpp"

#include <magic_enum.hpp>

namespace utils
{

M module-utils/bootconfig/src/bootconfig.cpp => module-utils/bootconfig/src/bootconfig.cpp +2 -2
@@ 149,7 149,7 @@ namespace boot
            m_os_root_path       = purefs::createPath(purefs::dir::getRootDiskPath(), m_os_type);
            m_boot_json          = bootJsonPath;
            m_bootloader_version = m_boot_json_parsed[boot::json::bootloader][boot::json::os_version].string_value();
            m_timestamp          = utils::time::Timestamp().str("%c");
            m_timestamp          = utils::time::getCurrentTimestamp().str("%c");
            m_os_version         = std::string(VERSION);

            LOG_INFO("boot_config: %s", to_json().dump().c_str());


@@ 160,7 160,7 @@ namespace boot
            m_os_image     = purefs::file::boot_bin;
            m_os_root_path = purefs::createPath(purefs::dir::getRootDiskPath(), m_os_type);
            m_boot_json    = bootJsonPath;
            m_timestamp    = utils::time::Timestamp().str("%c");
            m_timestamp    = utils::time::getCurrentTimestamp().str("%c");
            m_os_version   = std::string(VERSION);
            LOG_WARN("%s failed to parse %s: \"%s\"", __FUNCTION__, bootJsonPath.c_str(), parseErrors.c_str());
            return false;

M module-utils/time/time_conversion.cpp => module-utils/time/time_conversion.cpp +3 -25
@@ 56,7 56,6 @@ namespace utils::time
    } // namespace

    Locale tlocale;
    static int msTimeGmtOff = 4 * utils::time::minutesInQuarterOfHour * utils::time::secondsInMinute;

    UTF8 Localer::get_replacement(Replacements val, const struct tm &timeinfo)
    {


@@ 82,12 81,8 @@ namespace utils::time

    Timestamp::Timestamp()
    {
        auto err = bsp::rtc::getCurrentTimestamp(&time);
        time += utils::time::Time::getTimeZoneOffset();
        if (err != bsp::rtc::ErrorCode::OK) {
            LOG_ERROR("rtc::getCurrentTimestamp failure!");
        }
        timeinfo = *localtime(&time);
        time     = 0;
        timeinfo = *std::localtime(&time);
    }

    void Timestamp::set_time(time_t newtime)


@@ 284,16 279,6 @@ namespace utils::time
        }
    }

    void Time::setTimeZoneOffset(int tzOffset)
    {
        msTimeGmtOff = tzOffset;
    }

    int Time::getTimeZoneOffset()
    {
        return msTimeGmtOff;
    };

    Duration::Duration(time_t duration) : duration(duration)
    {
        calculate();


@@ 345,13 330,6 @@ namespace utils::time

    Timestamp getCurrentTimestamp()
    {
        return Timestamp{};
    }

    std::string getHoursMinInCurrentTimeFormat()
    {
        auto timestamp = getCurrentTimestamp();
        return utils::dateAndTimeSettings.isTimeFormat12() ? timestamp.str(hoursMinFormat12H)
                                                           : timestamp.str(hoursMinFormat24H);
        return Timestamp{std::time(nullptr)};
    }
}; // namespace utils::time

M module-utils/time/time_conversion.hpp => module-utils/time/time_conversion.hpp +2 -7
@@ 153,7 153,8 @@ namespace utils
            std::string long_ago_format = "%d.%m.%y";

            /// shows time in past: time_now - val in seconds
            DateTime(time_t val = 0, bool date_format_long = true) : date_format_long(date_format_long)
            DateTime(time_t val = 0, bool date_format_long = true)
                : Timestamp(std::time(nullptr)), date_format_long(date_format_long)
            {
                before_n_sec(val);
            }


@@ 185,11 186,6 @@ namespace utils
          public:
            Time(time_t val = 0, bool date_format_long = true) : DateTime(val, date_format_long){};
            virtual UTF8 str(std::string format = "") final;

            /// set time zone offset including adjustment for daylight saving
            static void setTimeZoneOffset(int tzOffset);
            // get time zone offset including adjustment for daylight saving
            static int getTimeZoneOffset();
        };

        class Duration


@@ 288,6 284,5 @@ namespace utils
        };

        Timestamp getCurrentTimestamp();
        std::string getHoursMinInCurrentTimeFormat();
    } // namespace time
} // namespace utils