From b0f9ab8ac6047b9f0347cbeed44da87815884bcb Mon Sep 17 00:00:00 2001 From: hui1975 Date: Thu, 2 Mar 2023 12:42:15 +0000 Subject: [PATCH 01/53] =?UTF-8?q?sensor=E7=9C=81=E5=8A=9F=E8=80=97?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: I89bb0c0d794818cf70159b10cfbac1b64c1e0dc9 --- frameworks/native/sensor/BUILD.gn | 11 +- .../client_info_file_descriptor_listener.h | 40 ++ .../native/sensor/include/i_sensor_service.h | 17 +- .../sensor/include/sensor_agent_proxy.h | 7 +- .../sensor/include/sensor_data_channel.h | 15 +- .../sensor/include/sensor_service_client.h | 27 +- .../sensor/include/sensor_service_proxy.h | 9 +- .../client_info_file_descriptor_listener.cpp | 81 ++++ .../native/sensor/src/sensor_agent_proxy.cpp | 102 ++++- .../native/sensor/src/sensor_data_channel.cpp | 74 +++- .../sensor/src/sensor_service_client.cpp | 224 +++++++++- .../sensor/src/sensor_service_proxy.cpp | 185 +++++++- interfaces/native/BUILD.gn | 4 +- interfaces/native/include/sensor_agent.h | 49 ++- interfaces/native/include/sensor_agent_type.h | 12 +- interfaces/native/src/sensor_agent.cpp | 79 +++- interfaces/native/test/BUILD.gn | 42 +- .../test/unittest/sensor_power_test.cpp | 398 ++++++++++++++++++ interfaces/plugin/BUILD.gn | 4 +- services/sensor/BUILD.gn | 12 +- services/sensor/include/client_info.h | 9 + services/sensor/include/sensor_service.h | 17 +- services/sensor/include/sensor_service_stub.h | 9 +- .../sensor/include/sensor_suspend_policy.h | 59 +++ services/sensor/include/stream_server.h | 53 +++ services/sensor/src/client_info.cpp | 45 ++ services/sensor/src/sensor_service.cpp | 132 +++++- services/sensor/src/sensor_service_stub.cpp | 121 +++++- services/sensor/src/sensor_suspend_policy.cpp | 239 +++++++---- services/sensor/src/stream_server.cpp | 245 +++++++++++ test/unittest/common/include/system_info.h | 4 +- utils/BUILD.gn | 39 +- utils/common/BUILD.gn | 48 +++ utils/common/include/app_sensor.h | 61 +++ utils/{ => common}/include/app_thread_info.h | 0 .../include/death_recipient_template.h | 0 .../{ => common}/include/miscdevice_common.h | 0 utils/{ => common}/include/permission_util.h | 1 + .../include/report_data_callback.h | 0 utils/{ => common}/include/sensor.h | 0 .../include/sensor_basic_data_channel.h | 0 .../{ => common}/include/sensor_basic_info.h | 0 .../include/sensor_channel_info.h | 0 .../{ => common}/include/sensor_data_event.h | 0 utils/{ => common}/include/sensor_log.h | 0 utils/{ => common}/include/sensors_errors.h | 3 +- utils/common/src/app_sensor.cpp | 132 ++++++ utils/{ => common}/src/permission_util.cpp | 10 + .../{ => common}/src/report_data_callback.cpp | 0 utils/{ => common}/src/sensor.cpp | 0 .../src/sensor_basic_data_channel.cpp | 0 utils/{ => common}/src/sensor_basic_info.cpp | 0 .../{ => common}/src/sensor_channel_info.cpp | 0 utils/ipc/BUILD.gn | 46 ++ utils/ipc/include/circle_stream_buffer.h | 37 ++ utils/ipc/include/net_packet.h | 50 +++ utils/ipc/include/proto.h | 47 +++ utils/ipc/include/stream_buffer.h | 171 ++++++++ utils/ipc/include/stream_client.h | 55 +++ utils/ipc/include/stream_session.h | 74 ++++ utils/ipc/include/stream_socket.h | 59 +++ utils/ipc/src/circle_stream_buffer.cpp | 58 +++ utils/ipc/src/net_packet.cpp | 63 +++ utils/ipc/src/stream_buffer.cpp | 217 ++++++++++ utils/ipc/src/stream_client.cpp | 122 ++++++ utils/ipc/src/stream_session.cpp | 169 ++++++++ utils/ipc/src/stream_socket.cpp | 159 +++++++ 67 files changed, 3774 insertions(+), 172 deletions(-) create mode 100644 frameworks/native/sensor/include/client_info_file_descriptor_listener.h create mode 100644 frameworks/native/sensor/src/client_info_file_descriptor_listener.cpp create mode 100644 interfaces/native/test/unittest/sensor_power_test.cpp create mode 100644 services/sensor/include/sensor_suspend_policy.h create mode 100644 services/sensor/include/stream_server.h create mode 100644 services/sensor/src/stream_server.cpp create mode 100644 utils/common/BUILD.gn create mode 100644 utils/common/include/app_sensor.h rename utils/{ => common}/include/app_thread_info.h (100%) rename utils/{ => common}/include/death_recipient_template.h (100%) rename utils/{ => common}/include/miscdevice_common.h (100%) rename utils/{ => common}/include/permission_util.h (96%) rename utils/{ => common}/include/report_data_callback.h (100%) rename utils/{ => common}/include/sensor.h (100%) rename utils/{ => common}/include/sensor_basic_data_channel.h (100%) rename utils/{ => common}/include/sensor_basic_info.h (100%) rename utils/{ => common}/include/sensor_channel_info.h (100%) rename utils/{ => common}/include/sensor_data_event.h (100%) rename utils/{ => common}/include/sensor_log.h (100%) rename utils/{ => common}/include/sensors_errors.h (99%) create mode 100644 utils/common/src/app_sensor.cpp rename utils/{ => common}/src/permission_util.cpp (90%) rename utils/{ => common}/src/report_data_callback.cpp (100%) rename utils/{ => common}/src/sensor.cpp (100%) rename utils/{ => common}/src/sensor_basic_data_channel.cpp (100%) rename utils/{ => common}/src/sensor_basic_info.cpp (100%) rename utils/{ => common}/src/sensor_channel_info.cpp (100%) create mode 100644 utils/ipc/BUILD.gn create mode 100644 utils/ipc/include/circle_stream_buffer.h create mode 100644 utils/ipc/include/net_packet.h create mode 100644 utils/ipc/include/proto.h create mode 100644 utils/ipc/include/stream_buffer.h create mode 100644 utils/ipc/include/stream_client.h create mode 100644 utils/ipc/include/stream_session.h create mode 100644 utils/ipc/include/stream_socket.h create mode 100644 utils/ipc/src/circle_stream_buffer.cpp create mode 100644 utils/ipc/src/net_packet.cpp create mode 100644 utils/ipc/src/stream_buffer.cpp create mode 100644 utils/ipc/src/stream_client.cpp create mode 100644 utils/ipc/src/stream_session.cpp create mode 100644 utils/ipc/src/stream_socket.cpp diff --git a/frameworks/native/sensor/BUILD.gn b/frameworks/native/sensor/BUILD.gn index 9f9c6c3f..9fbac926 100755 --- a/frameworks/native/sensor/BUILD.gn +++ b/frameworks/native/sensor/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -25,16 +25,21 @@ ohos_shared_library("libsensor_native") { "src/sensor_file_descriptor_listener.cpp", "src/sensor_service_client.cpp", "src/sensor_service_proxy.cpp", + "src/client_info_file_descriptor_listener.cpp", ] include_dirs = [ "include", "//commonlibrary/c_utils/base/include", "//utils/system/safwk/native/include", - "$SUBSYSTEM_DIR/sensor/utils/include", + "$SUBSYSTEM_DIR/sensor/utils/common/include", + "$SUBSYSTEM_DIR/sensor/utils/ipc/include", "$SUBSYSTEM_DIR/sensor/interfaces/native/include", ] - deps = [ "$SUBSYSTEM_DIR/sensor/utils:libsensor_utils" ] + deps = [ + "$SUBSYSTEM_DIR/sensor/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/sensor/utils/ipc:libsensor_ipc", + ] external_deps = [ "c_utils:utils", diff --git a/frameworks/native/sensor/include/client_info_file_descriptor_listener.h b/frameworks/native/sensor/include/client_info_file_descriptor_listener.h new file mode 100644 index 00000000..ec107974 --- /dev/null +++ b/frameworks/native/sensor/include/client_info_file_descriptor_listener.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CLIENT_INFO_FILE_DESCRIPTOR_LISTENER_H +#define CLIENT_INFO_FILE_DESCRIPTOR_LISTENER_H + +#include "file_descriptor_listener.h" + +#include "sensor_data_channel.h" + +namespace OHOS { +namespace Sensors { +class ClientInfoFileDescriptorListener : public AppExecFwk::FileDescriptorListener { +public: + ClientInfoFileDescriptorListener() = default; + ~ClientInfoFileDescriptorListener() override = default; + void OnReadable(int32_t fd) override; + void OnShutdown(int32_t fd) override; + void OnException(int32_t fd) override; + void SetChannel(SensorDataChannel *channel); + DISALLOW_COPY_AND_MOVE(ClientInfoFileDescriptorListener); + +private: + SensorDataChannel *channel_ = nullptr; +}; +} // namespace Sensors +} // namespace OHOS +#endif // CLIENT_INFO_FILE_DESCRIPTOR_LISTENER_H diff --git a/frameworks/native/sensor/include/i_sensor_service.h b/frameworks/native/sensor/include/i_sensor_service.h index dab25cb4..23ca0c08 100755 --- a/frameworks/native/sensor/include/i_sensor_service.h +++ b/frameworks/native/sensor/include/i_sensor_service.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,6 +21,7 @@ #include "errors.h" #include "iremote_broker.h" +#include "app_sensor.h" #include "i_sensor_client.h" #include "sensor_basic_data_channel.h" #include "sensor.h" @@ -39,6 +40,13 @@ public: virtual ErrCode TransferDataChannel(const sptr &sensorBasicDataChannel, const sptr &sensorClient) = 0; virtual ErrCode DestroySensorChannel(sptr sensorClient) = 0; + virtual ErrCode SuspendSensors(int32_t pid) = 0; + virtual ErrCode ResumeSensors(int32_t pid) = 0; + virtual ErrCode GetAppSensorList(int32_t pid, std::vector &appSensorList) = 0; + virtual ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) = 0; + virtual ErrCode DestroySocketChannel(const sptr &sensorClient) = 0; + virtual ErrCode EnableClientInfoCallback() = 0; + virtual ErrCode DisableClientInfoCallback() = 0; enum { ENABLE_SENSOR = 0, DISABLE_SENSOR, @@ -47,6 +55,13 @@ public: GET_SENSOR_LIST, TRANSFER_DATA_CHANNEL, DESTROY_SENSOR_CHANNEL, + SUSPEND_SENSORS, + RESUME_SENSORS, + GET_APP_SENSOR_LIST, + CREATE_SOCKET_CHANNEL, + DESTROY_SOCKET_CHANNEL, + ENABLE_CLIENT_INFO_CALLBACK, + DISABLE_CLIENT_INFO_CALLBACK, }; }; } // namespace Sensors diff --git a/frameworks/native/sensor/include/sensor_agent_proxy.h b/frameworks/native/sensor/include/sensor_agent_proxy.h index a14ea60d..d4259ef4 100644 --- a/frameworks/native/sensor/include/sensor_agent_proxy.h +++ b/frameworks/native/sensor/include/sensor_agent_proxy.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -43,6 +43,11 @@ public: int32_t SetMode(int32_t sensorId, const SensorUser *user, int32_t mode) const; int32_t SetOption(int32_t sensorId, const SensorUser *user, int32_t option) const; int32_t GetAllSensors(SensorInfo **sensorInfo, int32_t *count) const; + int32_t SuspendSensors(int32_t pid) const; + int32_t ResumeSensors(int32_t pid) const; + int32_t GetAppSensors(int32_t pid, AppSensorInfo **appSensorInfos, int32_t *count) const; + int32_t RegisterClientInfoCallback(ClientInfoCallback callback) const; + int32_t UnregisterClientInfoCallback(ClientInfoCallback callback) const; private: int32_t CreateSensorDataChannel() const; diff --git a/frameworks/native/sensor/include/sensor_data_channel.h b/frameworks/native/sensor/include/sensor_data_channel.h index ecf87bac..1b004337 100644 --- a/frameworks/native/sensor/include/sensor_data_channel.h +++ b/frameworks/native/sensor/include/sensor_data_channel.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,6 +18,8 @@ #include #include +#include +#include #include "sensor_agent_type.h" #include "sensor_event_handler.h" @@ -28,6 +30,9 @@ namespace Sensors { typedef void (*DataChannelCB)(SensorEvent *events, int32_t num, void *data); class SensorDataChannel : public SensorBasicDataChannel { public: + using ReceiveMessageFun = std::function; + using DisconnectFun = std::function; + SensorDataChannel() = default; ~SensorDataChannel(); static int32_t HandleEvent(int32_t fd, int32_t events, void *data); @@ -40,13 +45,19 @@ public: DataChannelCB dataCB_ = nullptr; void *privateData_ = nullptr; + int32_t AddFdListener(int32_t fd, ReceiveMessageFun receiveMessage, DisconnectFun disconnect); + int32_t DelFdListener(int32_t fd); + ReceiveMessageFun receiveMessage_; + DisconnectFun disconnect_; + private: static void ThreadProcessTask(SensorDataChannel *sensorChannel); int32_t InnerSensorDataChannel(); std::mutex eventRunnerMutex_; - static std::shared_ptr eventHandler_; + std::shared_ptr eventHandler_; static std::shared_ptr eventRunner_; static int32_t receiveFd_; + std::unordered_set listenedFdSet_; }; } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/sensor/include/sensor_service_client.h b/frameworks/native/sensor/include/sensor_service_client.h index ce45bad0..722fb5c3 100755 --- a/frameworks/native/sensor/include/sensor_service_client.h +++ b/frameworks/native/sensor/include/sensor_service_client.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,11 +17,13 @@ #define SENSOR_SERVICE_CLIENT_H #include +#include #include #include "iservice_registry.h" #include "singleton.h" +#include "app_sensor.h" #include "sensor_agent_type.h" #include "sensor_basic_data_channel.h" #include "sensor_basic_info.h" @@ -29,12 +31,13 @@ #include "sensor_data_channel.h" #include "sensor.h" #include "sensor_service_proxy.h" - +#include "stream_socket.h" namespace OHOS { namespace Sensors { -class SensorServiceClient : public Singleton { +class SensorServiceClient : public StreamSocket, public Singleton { public: + ~SensorServiceClient(); std::vector GetSensorList(); int32_t EnableSensor(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay); int32_t DisableSensor(int32_t sensorId); @@ -42,6 +45,15 @@ public: int32_t DestroyDataChannel(); void ProcessDeathObserver(const wptr &object); bool IsValid(int32_t sensorId); + int32_t SuspendSensors(int32_t pid); + int32_t ResumeSensors(int32_t pid); + int32_t GetAppSensorList(int32_t pid, std::vector &appSensorList); + + int32_t RegisterClientInfoCallback(ClientInfoCallback callback, sptr sensorDataChannel); + int32_t UnregisterClientInfoCallback(ClientInfoCallback callback); + + void ReceiveMessage(const char *buf, size_t size); + void Disconnect(); private: int32_t InitServiceClient(); @@ -55,8 +67,15 @@ private: sptr sensorClientStub_; std::mutex mapMutex_; std::map sensorInfoMap_; + + void HandleNetPacke(NetPacket &pkt); + void ReregisterClientInfoCallback(); + std::atomic_bool isConnected_ = false; + CircleStreamBuffer circBuf_; + + std::mutex clientInfoCallbackMutex_; + std::set clientInfoCallbackSet_; }; } // namespace Sensors } // namespace OHOS - #endif // SENSOR_SERVICE_CLIENT_H diff --git a/frameworks/native/sensor/include/sensor_service_proxy.h b/frameworks/native/sensor/include/sensor_service_proxy.h index 01bfde3e..efabec2a 100755 --- a/frameworks/native/sensor/include/sensor_service_proxy.h +++ b/frameworks/native/sensor/include/sensor_service_proxy.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -35,6 +35,13 @@ public: ErrCode TransferDataChannel(const sptr &sensorBasicDataChannel, const sptr &sensorClient) override; ErrCode DestroySensorChannel(sptr sensorClient) override; + ErrCode SuspendSensors(int32_t pid) override; + ErrCode ResumeSensors(int32_t pid) override; + ErrCode GetAppSensorList(int32_t pid, std::vector &appSensorList) override; + ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) override; + ErrCode DestroySocketChannel(const sptr &sensorClient) override; + ErrCode EnableClientInfoCallback() override; + ErrCode DisableClientInfoCallback() override; private: DISALLOW_COPY_AND_MOVE(SensorServiceProxy); diff --git a/frameworks/native/sensor/src/client_info_file_descriptor_listener.cpp b/frameworks/native/sensor/src/client_info_file_descriptor_listener.cpp new file mode 100644 index 00000000..3e9a3d0c --- /dev/null +++ b/frameworks/native/sensor/src/client_info_file_descriptor_listener.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "client_info_file_descriptor_listener.h" + +#include + +#include "sensors_errors.h" +#include "stream_socket.h" + +namespace OHOS { +namespace Sensors { +using namespace OHOS::AppExecFwk; +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "ClientInfoFileDescriptorListener" }; +} + +void ClientInfoFileDescriptorListener::SetChannel(SensorDataChannel *channel) +{ + channel_ = channel; +} + +void ClientInfoFileDescriptorListener::OnReadable(int32_t fd) +{ + if (fd < 0) { + SEN_HILOGE("Invalid fd:%{public}d", fd); + return; + } + char szBuf[PROTO_MAX_PACKET_BUF_SIZE] = {}; + for (int32_t i = 0; i < PROTO_MAX_RECV_LIMIT; i++) { + ssize_t size = recv(fd, szBuf, PROTO_MAX_PACKET_BUF_SIZE, MSG_DONTWAIT | MSG_NOSIGNAL); + if (size > 0) { + channel_->receiveMessage_(szBuf, size); + } else if (size < 0) { + if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) { + SEN_HILOGW("Continue for errno EAGAIN|EINTR|EWOULDBLOCK, size:%{public}zu, errno:%{public}d", + size, errno); + continue; + } + SEN_HILOGE("Recv return %{public}zu, errno:%{public}d", size, errno); + break; + } else { + SEN_HILOGD("The service side disconnect with the client. size:0, count:%{public}d, errno:%{public}d", + i, errno); + break; + } + if (size < PROTO_MAX_PACKET_BUF_SIZE) { + break; + } + } +} + +void ClientInfoFileDescriptorListener::OnShutdown(int32_t fd) +{ + if (fd < 0) { + SEN_HILOGE("Invalid fd:%{public}d", fd); + } + channel_->disconnect_(); +} + +void ClientInfoFileDescriptorListener::OnException(int32_t fd) +{ + if (fd < 0) { + SEN_HILOGE("Invalid fd:%{public}d", fd); + } + channel_->disconnect_(); +} +} // namespace Sensors +} // namespace OHOS diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index 21c46715..0959dae4 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,6 +18,7 @@ #include #include "securec.h" + #include "sensor_service_client.h" #include "sensors_errors.h" @@ -38,6 +39,8 @@ std::recursive_mutex SensorAgentProxy::subscribeMutex_; std::mutex SensorAgentProxy::chanelMutex_; std::mutex sensorInfoMutex_; SensorInfo *sensorInfos_ = nullptr; +std::mutex appSensorInfoMutex_; +AppSensorInfo *appSensorInfo_ = nullptr; int32_t sensorInfoCount_ = 0; std::map SensorAgentProxy::g_subscribeMap; std::map SensorAgentProxy::g_unsubscribeMap; @@ -266,6 +269,10 @@ int32_t SensorAgentProxy::SetMode(int32_t sensorId, const SensorUser *user, int3 void SensorAgentProxy::ClearSensorInfos() const { + if (appSensorInfo_ != nullptr) { + free(appSensorInfo_); + appSensorInfo_ = nullptr; + } CHKPV(sensorInfos_); free(sensorInfos_); sensorInfos_ = nullptr; @@ -330,5 +337,98 @@ int32_t SensorAgentProxy::GetAllSensors(SensorInfo **sensorInfo, int32_t *count) *count = sensorInfoCount_; return SUCCESS; } + +int32_t SensorAgentProxy::SuspendSensors(int32_t pid) const +{ + CALL_LOG_ENTER; + if (pid < 0) { + SEN_HILOGE("Pid is invalid, %{public}d", pid); + return PARAMETER_ERROR; + } + int32_t ret = SenClient.SuspendSensors(pid); + if (ret != 0) { + SEN_HILOGE("Suspend pid sensors failed, ret:%{public}d", ret); + } + return ret; +} + +int32_t SensorAgentProxy::ResumeSensors(int32_t pid) const +{ + CALL_LOG_ENTER; + if (pid < 0) { + SEN_HILOGE("Pid is invalid, %{public}d", pid); + return PARAMETER_ERROR; + } + int32_t ret = SenClient.ResumeSensors(pid); + if (ret != 0) { + SEN_HILOGE("Resume pid sensors failed, ret:%{public}d", ret); + } + return ret; +} + +int32_t SensorAgentProxy::GetAppSensors(int32_t pid, AppSensorInfo **appSensorInfos, int32_t *count) const +{ + CALL_LOG_ENTER; + if (pid < 0) { + SEN_HILOGE("Pid is invalid, %{public}d", pid); + return PARAMETER_ERROR; + } + CHKPR(appSensorInfos, OHOS::Sensors::ERROR); + CHKPR(count, OHOS::Sensors::ERROR); + std::lock_guard appSensorInfoLock(appSensorInfoMutex_); + if (appSensorInfo_ != nullptr) { + free(appSensorInfo_); + appSensorInfo_ = nullptr; + } + std::vector appSensorList; + int32_t ret = SenClient.GetAppSensorList(pid, appSensorList); + if (ret != 0) { + SEN_HILOGE("Get app sensor list failed, ret:%{public}d", ret); + return ERROR; + } + if (appSensorList.empty()) { + SEN_HILOGE("App sensor list is empty, pid:%{public}d", pid); + return ERROR; + } + size_t appSensorInfoCount = appSensorList.size(); + if (appSensorInfoCount > MAX_SENSOR_LIST_SIZE) { + SEN_HILOGE("The number of app sensors exceeds the maximum value, count:%{public}d", appSensorInfoCount); + return ERROR; + } + appSensorInfo_ = (AppSensorInfo *)malloc(sizeof(AppSensorInfo) * appSensorInfoCount); + CHKPR(appSensorInfo_, ERROR); + for (size_t i = 0; i < appSensorInfoCount; ++i) { + AppSensorInfo *curAppSensor = appSensorInfo_ + i; + curAppSensor->pid = appSensorList[i].GetPid(); + curAppSensor->sensorId = appSensorList[i].GetSensorId(); + curAppSensor->isActive = appSensorList[i].IsActive(); + curAppSensor->samplingPeriodNs = appSensorList[i].GetSamplingPeriodNs(); + curAppSensor->maxReportDelayNs = appSensorList[i].GetMaxReportDelayNs(); + } + *appSensorInfos = appSensorInfo_; + *count = static_cast(appSensorInfoCount); + return SUCCESS; +} + +int32_t SensorAgentProxy::RegisterClientInfoCallback(ClientInfoCallback callback) const +{ + CHKPR(callback, OHOS::Sensors::ERROR); + CHKPR(dataChannel_, INVALID_POINTER); + int32_t ret = SenClient.RegisterClientInfoCallback(callback, dataChannel_); + if (ret != ERR_OK) { + SEN_HILOGE("RegisterClientInfoCallback failed"); + } + return SUCCESS; +} + +int32_t SensorAgentProxy::UnregisterClientInfoCallback(ClientInfoCallback callback) const +{ + CHKPR(callback, OHOS::Sensors::ERROR); + int32_t ret = SenClient.UnregisterClientInfoCallback(callback); + if (ret != ERR_OK) { + SEN_HILOGE("UnregisterClientInfoCallback failed"); + } + return SUCCESS; +} } // namespace Sensors } // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/sensor/src/sensor_data_channel.cpp b/frameworks/native/sensor/src/sensor_data_channel.cpp index 501a6d0e..29405216 100644 --- a/frameworks/native/sensor/src/sensor_data_channel.cpp +++ b/frameworks/native/sensor/src/sensor_data_channel.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,14 +16,14 @@ #include "sensor_data_channel.h" #include "errors.h" + +#include "client_info_file_descriptor_listener.h" #include "sensor_file_descriptor_listener.h" #include "sensors_errors.h" - namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; using namespace OHOS::AppExecFwk; -std::shared_ptr SensorDataChannel::eventHandler_; namespace { constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SensorDataChannel" }; @@ -58,9 +58,11 @@ int32_t SensorDataChannel::InnerSensorDataChannel() } auto listener = std::make_shared(); listener->SetChannel(this); - auto myRunner = AppExecFwk::EventRunner::Create(true); - CHKPR(myRunner, ERROR); - eventHandler_ = std::make_shared(myRunner); + if (eventHandler_ == nullptr) { + auto myRunner = AppExecFwk::EventRunner::Create(true); + CHKPR(myRunner, ERROR); + eventHandler_ = std::make_shared(myRunner); + } int32_t receiveFd = GetReceiveDataFd(); auto inResult = eventHandler_->AddFileDescriptorListener(receiveFd, AppExecFwk::FILE_DESCRIPTOR_INPUT_EVENT, listener); @@ -68,6 +70,11 @@ int32_t SensorDataChannel::InnerSensorDataChannel() SEN_HILOGE("AddFileDescriptorListener fail"); return ERROR; } + auto pairRet = listenedFdSet_.insert(receiveFd); + if (!pairRet.second) { + SEN_HILOGE("ListenedFdSet insert fd fail"); + return ERROR; + } return ERR_OK; } @@ -75,8 +82,16 @@ int32_t SensorDataChannel::DestroySensorDataChannel() { std::lock_guard eventRunnerLock(eventRunnerMutex_); CHKPL(eventHandler_); - eventHandler_ = nullptr; - // destroy sensor basic channelx + int32_t receiveFd = GetReceiveDataFd(); + eventHandler_->RemoveFileDescriptorListener(receiveFd); + auto it = listenedFdSet_.find(receiveFd); + if (it != listenedFdSet_.end()) { + listenedFdSet_.erase(it); + } + if (eventHandler_ != nullptr && listenedFdSet_.empty()) { + eventHandler_ = nullptr; + SEN_HILOGI("Set eventHandler_ nullptr"); + } return DestroySensorBasicChannel(); } @@ -84,5 +99,48 @@ SensorDataChannel::~SensorDataChannel() { DestroySensorDataChannel(); } + +int32_t SensorDataChannel::AddFdListener(int32_t fd, ReceiveMessageFun receiveMessage, DisconnectFun disconnect) +{ + receiveMessage_ = receiveMessage; + disconnect_ = disconnect; + std::lock_guard eventRunnerLock(eventRunnerMutex_); + if (eventHandler_ == nullptr) { + auto myRunner = AppExecFwk::EventRunner::Create(true); + CHKPR(myRunner, ERROR); + eventHandler_ = std::make_shared(myRunner); + } + auto listener = std::make_shared(); + listener->SetChannel(this); + auto errCode = eventHandler_->AddFileDescriptorListener(fd, AppExecFwk::FILE_DESCRIPTOR_INPUT_EVENT, listener); + if (errCode != ERR_OK) { + SEN_HILOGE("Add fd listener failed, fd:%{public}d, errCode:%{public}u", fd, errCode); + return ERROR; + } + auto pairRet = listenedFdSet_.insert(fd); + if (!pairRet.second) { + SEN_HILOGE("ListenedFdSet insert fd fail"); + return ERROR; + } + return ERR_OK; +} + +int32_t SensorDataChannel::DelFdListener(int32_t fd) +{ + std::lock_guard eventRunnerLock(eventRunnerMutex_); + CHKPL(eventHandler_); + eventHandler_->RemoveFileDescriptorListener(fd); + auto it = listenedFdSet_.find(fd); + if (it == listenedFdSet_.end()) { + SEN_HILOGE("ListenedFdSet not find fd, fd:%{public}d", fd); + return ERROR; + } + listenedFdSet_.erase(it); + if (eventHandler_ != nullptr && listenedFdSet_.empty()) { + eventHandler_ = nullptr; + SEN_HILOGI("Set eventHandler_ nullptr"); + } + return ERR_OK; +} } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index 419f0e14..7f237cc8 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -38,6 +38,11 @@ constexpr int32_t GET_SERVICE_MAX_COUNT = 30; constexpr uint32_t WAIT_MS = 200; } // namespace +SensorServiceClient::~SensorServiceClient() +{ + Disconnect(); +} + int32_t SensorServiceClient::InitServiceClient() { CALL_LOG_ENTER; @@ -182,7 +187,6 @@ void SensorServiceClient::ProcessDeathObserver(const wptr &object dataChannel_->DestroySensorDataChannel(); // STEP2 : Restore data channel dataChannel_->RestoreSensorDataChannel(); - // STEP3 : Clear sensorlist and sensorServer_ sensorList_.clear(); sensorServer_ = nullptr; @@ -200,6 +204,12 @@ void SensorServiceClient::ProcessDeathObserver(const wptr &object for (const auto &it : sensorInfoMap_) { sensorServer_->EnableSensor(it.first, it.second.GetSamplingPeriodNs(), it.second.GetMaxReportDelayNs()); } + + if (!isConnected_) { + SEN_HILOGI("Previous socket channel status is false, not need retry creat socket channel"); + return; + } + ReregisterClientInfoCallback(); } void SensorServiceClient::UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay) @@ -224,5 +234,215 @@ void SensorServiceClient::DeleteSensorInfoItem(int32_t sensorId) } return; } + +int32_t SensorServiceClient::SuspendSensors(int32_t pid) +{ + CALL_LOG_ENTER; + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return ret; + } + CHKPR(sensorServer_, ERROR); + StartTrace(HITRACE_TAG_SENSORS, "SuspendSensors"); + ret = sensorServer_->SuspendSensors(pid); + FinishTrace(HITRACE_TAG_SENSORS); + return ret; +} + +int32_t SensorServiceClient::ResumeSensors(int32_t pid) +{ + CALL_LOG_ENTER; + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return ret; + } + CHKPR(sensorServer_, ERROR); + StartTrace(HITRACE_TAG_SENSORS, "ResumeSensors"); + ret = sensorServer_->ResumeSensors(pid); + FinishTrace(HITRACE_TAG_SENSORS); + return ret; +} +int32_t SensorServiceClient::GetAppSensorList(int32_t pid, std::vector &appSensorList) +{ + CALL_LOG_ENTER; + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return ret; + } + CHKPR(sensorServer_, ERROR); + StartTrace(HITRACE_TAG_SENSORS, "GetAppSensorList"); + ret = sensorServer_->GetAppSensorList(pid, appSensorList); + FinishTrace(HITRACE_TAG_SENSORS); + return ret; +} + +int32_t SensorServiceClient::RegisterClientInfoCallback(ClientInfoCallback callback, sptr sensorDataChannel) +{ + CALL_LOG_ENTER; + if (!isConnected_) { + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return ret; + } + CHKPR(sensorServer_, ERROR); + int32_t clientFd = -1; + StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel"); + ret = sensorServer_->CreateSocketChannel(clientFd, sensorClientStub_); + FinishTrace(HITRACE_TAG_SENSORS); + if (ret != ERR_OK) { + Close(); + SEN_HILOGE("Create socket channel failed"); + return ret; + } + if (clientFd < 0) { + Close(); + SEN_HILOGE("socketFd is invalid"); + return ERROR; + } + fd_ = clientFd; + dataChannel_ = sensorDataChannel; + if (dataChannel_->AddFdListener(fd_, + std::bind(&SensorServiceClient::ReceiveMessage, this, std::placeholders::_1, std::placeholders::_2), + std::bind(&SensorServiceClient::Disconnect, this)) != ERR_OK) { + Close(); + SEN_HILOGE("Add fd listener failed"); + return ERROR; + } + StartTrace(HITRACE_TAG_SENSORS, "EnableClientInfoCallback"); + ret = sensorServer_->EnableClientInfoCallback(); + FinishTrace(HITRACE_TAG_SENSORS); + if (ret != ERR_OK) { + SEN_HILOGE("Enable clientInfo callback failed"); + Disconnect(); + return ret; + } + isConnected_ = true; + } + std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); + clientInfoCallbackSet_.insert(callback); + return ERR_OK; +} + +int32_t SensorServiceClient::UnregisterClientInfoCallback(ClientInfoCallback callback) +{ + CALL_LOG_ENTER; + std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); + clientInfoCallbackSet_.erase(callback); + if (!clientInfoCallbackSet_.empty()) { + return ERR_OK; + } + Disconnect(); + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return ret; + } + CHKPR(sensorServer_, ERROR); + StartTrace(HITRACE_TAG_SENSORS, "DisableClientInfoCallback"); + ret = sensorServer_->DisableClientInfoCallback(); + FinishTrace(HITRACE_TAG_SENSORS); + if (ret != ERR_OK) { + SEN_HILOGE("Disable clientInfo callback failed"); + return ret; + } + StartTrace(HITRACE_TAG_SENSORS, "DestroySocketChannel"); + ret = sensorServer_->DestroySocketChannel(sensorClientStub_); + FinishTrace(HITRACE_TAG_SENSORS); + if (ret != ERR_OK) { + SEN_HILOGE("Destroy socket channel failed"); + return ret; + } + isConnected_ = false; + return ERR_OK; +} + +void SensorServiceClient::ReceiveMessage(const char *buf, size_t size) +{ + CHKPV(buf); + if (size == 0 || size > PROTO_MAX_PACKET_BUF_SIZE) { + SEN_HILOGE("Invalid input param size. size:%{public}zu", size); + return; + } + if (!circBuf_.Write(buf, size)) { + SEN_HILOGE("Write data failed. size:%{public}zu", size); + } + OnReadPackets(circBuf_, std::bind(&SensorServiceClient::HandleNetPacke, this, std::placeholders::_1)); +} + +void SensorServiceClient::HandleNetPacke(NetPacket &pkt) +{ + auto id = pkt.GetMsgId(); + if (id != MessageId::CLIENT_INFO) { + return; + } + AppSensorInfo appSensorInfo; + pkt >> appSensorInfo.pid >> appSensorInfo.sensorId >> appSensorInfo.isActive >> + appSensorInfo.samplingPeriodNs >> appSensorInfo.maxReportDelayNs; + if (pkt.ChkRWError()) { + SEN_HILOGE("Packet read type failed"); + return; + } + std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); + for (auto callback : clientInfoCallbackSet_) { + if (callback != nullptr) { + callback(&appSensorInfo); + } + } +} + +void SensorServiceClient::Disconnect() +{ + CALL_LOG_ENTER; + if (fd_ < 0) { + return; + } + int32_t ret = dataChannel_->DelFdListener(fd_); + if (ret != ERR_OK) { + SEN_HILOGE("Delete fd listener failed"); + } + Close(); +} + +void SensorServiceClient::ReregisterClientInfoCallback() +{ + CALL_LOG_ENTER; + Disconnect(); + int32_t clientFd = -1; + StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel"); + int32_t ret = sensorServer_->CreateSocketChannel(clientFd, sensorClientStub_); + FinishTrace(HITRACE_TAG_SENSORS); + if (ret != ERR_OK) { + Close(); + SEN_HILOGE("Create socket channel failed"); + return; + } + if (clientFd < 0) { + Close(); + SEN_HILOGE("socketFd is invalid"); + return; + } + fd_ = clientFd; + if (dataChannel_->AddFdListener(fd_, + std::bind(&SensorServiceClient::ReceiveMessage, this, std::placeholders::_1, std::placeholders::_2), + std::bind(&SensorServiceClient::Disconnect, this)) != ERR_OK) { + Close(); + SEN_HILOGE("Add fd listener failed"); + return; + } + StartTrace(HITRACE_TAG_SENSORS, "EnableClientInfoCallback"); + ret = sensorServer_->EnableClientInfoCallback(); + FinishTrace(HITRACE_TAG_SENSORS); + if (ret != ERR_OK) { + SEN_HILOGE("Enable clientInfo callback failed"); + Disconnect(); + return; + } + isConnected_ = true; + SEN_HILOGI("Client Retry Register Client Info Callback Success"); +} } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 5ed9c4b2..975ce441 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -190,5 +190,188 @@ ErrCode SensorServiceProxy::DestroySensorChannel(sptr sensorClien } return static_cast(ret); } + +ErrCode SensorServiceProxy::SuspendSensors(int32_t pid) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { + SEN_HILOGE("Write descriptor failed"); + return WRITE_MSG_ERR; + } + if (!data.WriteInt32(pid)) { + SEN_HILOGE("Write pid failed"); + return WRITE_MSG_ERR; + } + sptr remote = Remote(); + CHKPR(remote, ERROR); + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(ISensorService::SUSPEND_SENSORS, data, reply, option); + if (ret != NO_ERROR) { + HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SENSOR_SERVICE_IPC_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "SuspendSensors", "ERROR_CODE", ret); + SEN_HILOGE("Failed, ret:%{public}d", ret); + } + return static_cast(ret); +} + +ErrCode SensorServiceProxy::ResumeSensors(int32_t pid) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { + SEN_HILOGE("Write descriptor failed"); + return WRITE_MSG_ERR; + } + if (!data.WriteInt32(pid)) { + SEN_HILOGE("Write pid failed"); + return WRITE_MSG_ERR; + } + sptr remote = Remote(); + CHKPR(remote, ERROR); + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(ISensorService::RESUME_SENSORS, data, reply, option); + if (ret != NO_ERROR) { + HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SENSOR_SERVICE_IPC_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "ResumeSensors", "ERROR_CODE", ret); + SEN_HILOGE("Failed, ret:%{public}d", ret); + } + return static_cast(ret); +} + +ErrCode SensorServiceProxy::GetAppSensorList(int32_t pid, std::vector &appSensorList) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { + SEN_HILOGE("Write descriptor failed"); + return WRITE_MSG_ERR; + } + if (!data.WriteInt32(pid)) { + SEN_HILOGE("Write pid failed"); + return WRITE_MSG_ERR; + } + sptr remote = Remote(); + CHKPR(remote, ERROR); + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(ISensorService::GET_APP_SENSOR_LIST, data, reply, option); + if (ret != NO_ERROR) { + HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SENSOR_SERVICE_IPC_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "GetAppSensorList", "ERROR_CODE", ret); + SEN_HILOGE("Failed, ret:%{public}d", ret); + return static_cast(ret); + } + int32_t appSensorCount; + if (!reply.ReadInt32(appSensorCount)) { + SEN_HILOGE("Parcel read appSensorCount failed"); + return READ_MSG_ERR; + } + AppSensor appSensor; + for (int32_t i = 0; i < appSensorCount; ++i) { + auto tmpAppSensor = appSensor.Unmarshalling(reply); + if (tmpAppSensor == nullptr) { + SEN_HILOGE("Current appSensor is nullptr, i:%{public}d", i); + continue; + } + appSensorList.push_back(*tmpAppSensor); + } + return static_cast(ret); +} + +ErrCode SensorServiceProxy::CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) +{ + CHKPR(sensorClient, OBJECT_NULL); + MessageParcel data; + if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { + SEN_HILOGE("Write descriptor failed"); + return WRITE_MSG_ERR; + } + if (!data.WriteRemoteObject(sensorClient)) { + SEN_HILOGE("Write sensorClient failed"); + return WRITE_MSG_ERR; + } + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + CHKPR(remote, ERROR); + int32_t ret = remote->SendRequest(ISensorService::CREATE_SOCKET_CHANNEL, data, reply, option); + if (ret != NO_ERROR) { + HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SERVICE_IPC_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "CreateSocketChannel", "ERROR_CODE", ret); + SEN_HILOGE("failed, ret:%{public}d", ret); + return ERROR; + } + clientFd = reply.ReadFileDescriptor(); + if (clientFd < 0) { + SEN_HILOGE("Read file descriptor failed, fd: %{public}d", clientFd); + return ERROR; + } + return static_cast(ret); +} + +ErrCode SensorServiceProxy::DestroySocketChannel(const sptr &sensorClient) +{ + CHKPR(sensorClient, OBJECT_NULL); + MessageParcel data; + if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { + SEN_HILOGE("write descriptor failed"); + return WRITE_MSG_ERR; + } + if (!data.WriteRemoteObject(sensorClient)) { + SEN_HILOGE("Write sensorClient failed"); + return WRITE_MSG_ERR; + } + sptr remote = Remote(); + CHKPR(remote, ERROR); + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(ISensorService::DESTROY_SOCKET_CHANNEL, data, reply, option); + if (ret != NO_ERROR) { + HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SERVICE_IPC_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "DestroySocketChannel", "ERROR_CODE", ret); + SEN_HILOGE("failed, ret:%{public}d", ret); + } + return static_cast(ret); +} + +ErrCode SensorServiceProxy::EnableClientInfoCallback() +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { + SEN_HILOGE("write descriptor failed"); + return WRITE_MSG_ERR; + } + sptr remote = Remote(); + CHKPR(remote, ERROR); + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(ISensorService::ENABLE_CLIENT_INFO_CALLBACK, data, reply, option); + if (ret != NO_ERROR) { + HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SERVICE_IPC_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "EnableClientInfoCallback", "ERROR_CODE", ret); + SEN_HILOGE("failed, ret:%{public}d", ret); + } + return static_cast(ret); +} + +ErrCode SensorServiceProxy::DisableClientInfoCallback() +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { + SEN_HILOGE("write descriptor failed"); + return WRITE_MSG_ERR; + } + sptr remote = Remote(); + CHKPR(remote, ERROR); + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(ISensorService::DISABLE_CLIENT_INFO_CALLBACK, data, reply, option); + if (ret != NO_ERROR) { + HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SERVICE_IPC_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "DISABLE_CLIENT_INFO_CALLBACK", "ERROR_CODE", ret); + SEN_HILOGE("failed, ret:%{public}d", ret); + } + return static_cast(ret); +} } // namespace Sensors } // namespace OHOS diff --git a/interfaces/native/BUILD.gn b/interfaces/native/BUILD.gn index 1050549d..9e1bece6 100644 --- a/interfaces/native/BUILD.gn +++ b/interfaces/native/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -27,7 +27,7 @@ config("sensor_private_config") { "//commonlibrary/c_utils/base/include", "//utils/system/safwk/native/include", "$SUBSYSTEM_DIR/frameworks/native/sensor/include", - "$SUBSYSTEM_DIR/utils/include", + "$SUBSYSTEM_DIR/utils/common/include", "$SUBSYSTEM_DIR/interfaces/native/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//base/notification/eventhandler/interfaces/inner_api", diff --git a/interfaces/native/include/sensor_agent.h b/interfaces/native/include/sensor_agent.h index ead362c9..ff86b534 100755 --- a/interfaces/native/include/sensor_agent.h +++ b/interfaces/native/include/sensor_agent.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -127,6 +127,53 @@ int32_t DeactivateSensor(int32_t sensorTypeId, const SensorUser *user); * @since 5 */ int32_t SetMode(int32_t sensorTypeId, const SensorUser *user, int32_t mode); +/** + * @brief 休眠一个进程订阅的所有传感器 + * + * @param pid 进程号 + * @return 返回0表示成功,否则表示失败 + * + * @since 10 + */ +int32_t SuspendSensors(int32_t pid); +/** + * @brief 唤醒一个进程订阅的所有传感器 + * + * @param pid 进程号 + * @return 返回0表示成功,否则表示失败 + * + * @since 10 + */ +int32_t ResumeSensors(int32_t pid); +/** + * @brief 查询一个进程订阅的所有传感器的信息 + * + * @param pid 进程号 + * @param appSensorInfos 返回进程订阅的所有传感器信息 + * @param count 返回进程订阅的传感器数量 + * @return 返回0表示成功,否则表示失败 + * + * @since 10 + */ +int32_t GetAppSensors(int32_t pid, AppSensorInfo **appSensorInfos, int32_t *count); +/** + * @brief 注册传感器订阅信息上报函数 + * + * @param callback 回调函数 + * @return 返回0表示成功,否则表示失败 + * + * @since 10 + */ +int32_t RegisterClientInfoCallback(ClientInfoCallback callback); +/** + * @brief 取消注册传感器订阅信息上报函数 + * + * @param callback 回调函数 + * @return 返回0表示成功,否则表示失败 + * + * @since 10 + */ +int32_t UnregisterClientInfoCallback(ClientInfoCallback callback); #ifdef __cplusplus #if __cplusplus diff --git a/interfaces/native/include/sensor_agent_type.h b/interfaces/native/include/sensor_agent_type.h index 37b0de0e..eb1dc419 100644 --- a/interfaces/native/include/sensor_agent_type.h +++ b/interfaces/native/include/sensor_agent_type.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -395,6 +395,16 @@ typedef struct WearDetectionData { float value; } WearDetectionData; +typedef struct AppSensorInfo { + int32_t pid = -1; /**< PID */ + int32_t sensorId = -1; /**< Sensor ID */ + bool isActive = false; /**< Whether the process enable the sensor */ + int64_t samplingPeriodNs = -1; /**< Sample period, in ns */ + int64_t maxReportDelayNs = -1; /**< Maximum Report Delay, in ns */ +} AppSensorInfo; + +typedef void (*ClientInfoCallback)(AppSensorInfo *appSensorInfo); + #ifdef __cplusplus #if __cplusplus } diff --git a/interfaces/native/src/sensor_agent.cpp b/interfaces/native/src/sensor_agent.cpp index ccae1ff7..604def3c 100755 --- a/interfaces/native/src/sensor_agent.cpp +++ b/interfaces/native/src/sensor_agent.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -146,4 +146,81 @@ int32_t SetMode(int32_t sensorId, const SensorUser *user, int32_t mode) return SERVICE_EXCEPTION; } return proxy->SetMode(sensorId, user, mode); +} + +int32_t SuspendSensors(int32_t pid) +{ + const SensorAgentProxy *proxy = GetInstance(); + if (proxy == nullptr) { + SEN_HILOGE("Proxy is nullptr"); + return SERVICE_EXCEPTION; + } + int32_t ret = proxy->SuspendSensors(pid); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Suspend pid sensors failed, ret:%{public}d", ret); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t ResumeSensors(int32_t pid) +{ + const SensorAgentProxy *proxy = GetInstance(); + if (proxy == nullptr) { + SEN_HILOGE("Proxy is nullptr"); + return SERVICE_EXCEPTION; + } + int32_t ret = proxy->ResumeSensors(pid); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Resume pid sensors failed, ret:%{public}d", ret); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t GetAppSensors(int32_t pid, AppSensorInfo **appSensorInfos, int32_t *count) +{ + CHKPR(appSensorInfos, OHOS::Sensors::ERROR); + CHKPR(count, OHOS::Sensors::ERROR); + const SensorAgentProxy *proxy = GetInstance(); + if (proxy == nullptr) { + SEN_HILOGE("Proxy is nullptr"); + return SERVICE_EXCEPTION; + } + int32_t ret = proxy->GetAppSensors(pid, appSensorInfos, count); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("GetAppSensors failed, ret:%{public}d", ret); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t RegisterClientInfoCallback(ClientInfoCallback callback) +{ + const SensorAgentProxy *proxy = GetInstance(); + if (proxy == nullptr) { + SEN_HILOGE("proxy is nullptr"); + return SERVICE_EXCEPTION; + } + int32_t ret = proxy->RegisterClientInfoCallback(callback); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("RegisterClientInfoCallback failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t UnregisterClientInfoCallback(ClientInfoCallback callback) +{ + const SensorAgentProxy *proxy = GetInstance(); + if (proxy == nullptr) { + SEN_HILOGE("proxy is nullptr"); + return SERVICE_EXCEPTION; + } + int32_t ret = proxy->UnregisterClientInfoCallback(callback); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("UnregisterClientInfoCallback failed"); + return NormalizeErrCode(ret); + } + return ret; } \ No newline at end of file diff --git a/interfaces/native/test/BUILD.gn b/interfaces/native/test/BUILD.gn index 5a175be2..ea0d5c97 100644 --- a/interfaces/native/test/BUILD.gn +++ b/interfaces/native/test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -27,14 +27,14 @@ ohos_unittest("SensorAgentTest") { include_dirs = [ "//commonlibrary/c_utils/base/include", - "$SUBSYSTEM_DIR/sensor/utils/include", + "$SUBSYSTEM_DIR/sensor/utils/common/include", "$SUBSYSTEM_DIR/sensor/interfaces/native/include", "$SUBSYSTEM_DIR/sensor/test/unittest/common/include", ] deps = [ "$SUBSYSTEM_DIR/sensor/interfaces/native:sensor_ndk_target", - "$SUBSYSTEM_DIR/sensor/utils:libsensor_utils", + "$SUBSYSTEM_DIR/sensor/utils/common:libsensor_utils", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -55,14 +55,14 @@ ohos_unittest("SensorAlgorithmTest") { include_dirs = [ "//commonlibrary/c_utils/base/include", - "$SUBSYSTEM_DIR/sensor/utils/include", + "$SUBSYSTEM_DIR/sensor/utils/common/include", "$SUBSYSTEM_DIR/sensor/interfaces/native/include", "$SUBSYSTEM_DIR/sensor/test/unittest/common/include", ] deps = [ "$SUBSYSTEM_DIR/sensor/interfaces/native:sensor_ndk_target", - "$SUBSYSTEM_DIR/sensor/utils:libsensor_utils", + "$SUBSYSTEM_DIR/sensor/utils/common:libsensor_utils", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -73,11 +73,43 @@ ohos_unittest("SensorAlgorithmTest") { ] } +ohos_unittest("SensorPowerTest") { + module_out_path = module_output_path + + sources = [ + "$SUBSYSTEM_DIR/sensor/test/unittest/common/src/system_info.cpp", + "unittest/sensor_power_test.cpp", + ] + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "$SUBSYSTEM_DIR/sensor/utils/common/include", + "$SUBSYSTEM_DIR/sensor/interfaces/native/include", + "$SUBSYSTEM_DIR/sensor/test/unittest/common/include", + ] + + deps = [ + "$SUBSYSTEM_DIR/sensor/interfaces/native:sensor_ndk_target", + "$SUBSYSTEM_DIR/sensor/utils/common:libsensor_utils", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + ###########################end########################### group("unittest") { testonly = true deps = [ ":SensorAgentTest", ":SensorAlgorithmTest", + ":SensorPowerTest", ] } diff --git a/interfaces/native/test/unittest/sensor_power_test.cpp b/interfaces/native/test/unittest/sensor_power_test.cpp new file mode 100644 index 00000000..9e3f741a --- /dev/null +++ b/interfaces/native/test/unittest/sensor_power_test.cpp @@ -0,0 +1,398 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "accesstoken_kit.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" + +#include "sensor_agent.h" +#include "sensors_errors.h" +#include "system_info.h" + +namespace OHOS { +namespace Sensors { +using namespace testing::ext; +using namespace OHOS::HiviewDFX; +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; + +namespace { +constexpr HiLogLabel LABEL = { LOG_CORE, OHOS::Sensors::SENSOR_LOG_DOMAIN, "SensorPowerTest" }; +constexpr int32_t sensorId { 1 }; +constexpr int32_t invalidValue { -1 }; +} // namespace + +class SensorPowerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +int32_t process_pid = 0; + +void SensorPowerTest::SetUpTestCase() +{ + const char **perms = new const char *[1]; + perms[0] = "ohos.permission.ACCELEROMETER"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 1, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "SensorPowerTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(SetSelfTokenID(tokenId), 0); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; + + SYSTEM_INFO::CpuInfo cpuInfo; + const std::string process_name = "SensorPowerTest"; + process_pid = cpuInfo.GetTaskPidFile(process_name); + SEN_HILOGI("Current process pid is %{public}d", process_pid); + ASSERT_NE(process_pid, 0); +} + +void SensorPowerTest::TearDownTestCase() {} + +void SensorPowerTest::SetUp() {} + +void SensorPowerTest::TearDown() {} + +void SensorDataCallbackImpl(SensorEvent *event) +{ + if (event == nullptr) { + SEN_HILOGE("SensorEvent is null"); + return; + } + float *sensorData = (float *)event[0].data; + SEN_HILOGI("SensorId:%{public}d, version:%{public}d,dataLen:%{public}d,data:%{public}f", + event[0].sensorTypeId, event[0].version, event[0].dataLen, *(sensorData)); +} + +void ClientInfoCallbackImpl(AppSensorInfo *appSensorInfo) +{ + if (appSensorInfo == nullptr) { + SEN_HILOGE("appSensorInfo is null"); + return; + } + SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " + "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", + appSensorInfo->pid, appSensorInfo->sensorId, appSensorInfo->isActive, + appSensorInfo->samplingPeriodNs, appSensorInfo->maxReportDelayNs); +} + +void ClientInfoCallbackImpl2(AppSensorInfo *appSensorInfo) +{ + if (appSensorInfo == nullptr) { + SEN_HILOGE("appSensorInfo is null"); + return; + } + SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " + "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", + appSensorInfo->pid, appSensorInfo->sensorId, appSensorInfo->isActive, + appSensorInfo->samplingPeriodNs, appSensorInfo->maxReportDelayNs); +} + +HWTEST_F(SensorPowerTest, SuspendSensorsTest_001, TestSize.Level1) +{ + // 休眠接口异常用例 + SEN_HILOGI("SuspendSensorsTest_001 in"); + int32_t ret = SuspendSensors(invalidValue); + ASSERT_NE(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorPowerTest, ResumeSensorsTest_001, TestSize.Level1) +{ + // 恢复接口异常用例 + SEN_HILOGI("ResumeSensorsTest_001 in"); + int32_t ret = ResumeSensors(invalidValue); + ASSERT_NE(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorPowerTest, GetAppSensorsTest_001, TestSize.Level1) +{ + // 查询接口异常用例 + SEN_HILOGI("GetAppSensorsTest_001 in"); + AppSensorInfo *appSensorInfos {nullptr}; + int32_t count { 0 }; + int32_t ret = GetAppSensors(invalidValue, &appSensorInfos, &count); + ASSERT_NE(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorPowerTest, RegisterClientInfoCallback_001, TestSize.Level1) +{ + // 注册接口异常用例 + SEN_HILOGI("RegisterClientInfoCallback_001 in"); + ClientInfoCallback callback = nullptr; + int32_t ret = RegisterClientInfoCallback(callback); + ASSERT_NE(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorPowerTest, UnregisterClientInfoCallback_001, TestSize.Level1) +{ + // 取消注册接口异常用例 + SEN_HILOGI("UnregisterClientInfoCallback_001 in"); + ClientInfoCallback callback = nullptr; + int32_t ret = UnregisterClientInfoCallback(callback); + ASSERT_NE(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorPowerTest, SensorPowerTest_001, TestSize.Level1) +{ + // 场景用例1,订阅ACC传感器》查询传感器订阅数据》休眠进程的传感器》恢复进程的传感器》取消订阅ACC传感器 + SEN_HILOGI("SensorPowerTest_001 in"); + SensorUser user; + user.callback = SensorDataCallbackImpl; + + int32_t ret = SubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = SetBatch(sensorId, &user, 100000000, 100000000); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = ActivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + AppSensorInfo *appSensorInfos {nullptr}; + int32_t count { 0 }; + ret = GetAppSensors(process_pid, &appSensorInfos, &count); + for (int32_t i = 0; i < count; ++i) { + AppSensorInfo *curAppSensor = appSensorInfos + i; + SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " + "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", + i, curAppSensor->pid, curAppSensor->sensorId, curAppSensor->isActive, + curAppSensor->samplingPeriodNs, curAppSensor->maxReportDelayNs); + } + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + + ret = SuspendSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + + ret = ResumeSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + + ret = DeactivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = UnsubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorPowerTest, SensorPowerTest_002, TestSize.Level1) +{ + // 场景用例2,订阅ACC传感器》休眠进程的传感器》查询传感器订阅数据》恢复进程的传感器》取消订阅ACC传感器 + SEN_HILOGI("SensorPowerTest_002 in"); + SensorUser user; + user.callback = SensorDataCallbackImpl; + + int32_t ret = SubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = SetBatch(sensorId, &user, 100000000, 100000000); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = ActivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + ret = SuspendSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + + AppSensorInfo *appSensorInfos {nullptr}; + int32_t count { 0 }; + ret = GetAppSensors(process_pid, &appSensorInfos, &count); + for (int32_t i = 0; i < count; ++i) { + AppSensorInfo *curAppSensor = appSensorInfos + i; + SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " + "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", + i, curAppSensor->pid, curAppSensor->sensorId, curAppSensor->isActive, + curAppSensor->samplingPeriodNs, curAppSensor->maxReportDelayNs); + } + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + + ret = ResumeSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + + ret = DeactivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = UnsubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorPowerTest, SensorPowerTest_003, TestSize.Level1) +{ + // 场景用例3,订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》查询传感器订阅数据》取消订阅ACC传感器 + SEN_HILOGI("SensorPowerTest_003 in"); + SensorUser user; + user.callback = SensorDataCallbackImpl; + + int32_t ret = SubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = SetBatch(sensorId, &user, 100000000, 100000000); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = ActivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + ret = SuspendSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + + ret = ResumeSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + + AppSensorInfo *appSensorInfos {nullptr}; + int32_t count { 0 }; + ret = GetAppSensors(process_pid, &appSensorInfos, &count); + for (int32_t i = 0; i < count; ++i) { + AppSensorInfo *curAppSensor = appSensorInfos + i; + SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " + "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", + i, curAppSensor->pid, curAppSensor->sensorId, curAppSensor->isActive, + curAppSensor->samplingPeriodNs, curAppSensor->maxReportDelayNs); + } + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + + ret = DeactivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = UnsubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorPowerTest, SensorPowerTest_004, TestSize.Level1) +{ + // 场景用例4,注册回调函数》订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》取消订阅ACC传感器》取消注册回调函数 + SEN_HILOGI("SensorPowerTest_004 in"); + SensorUser user; + user.callback = SensorDataCallbackImpl; + ClientInfoCallback callback = ClientInfoCallbackImpl; + + int32_t ret = RegisterClientInfoCallback(callback); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + + ret = SubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = SetBatch(sensorId, &user, 100000000, 100000000); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = ActivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + ret = SuspendSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + + ret = ResumeSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + + ret = DeactivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = UnsubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + + ret = UnregisterClientInfoCallback(callback); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorPowerTest, SensorPowerTest_005, TestSize.Level1) +{ + // 场景用例5,注册回调函数》订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》取消注册回调函数》取消订阅ACC传感器 + SEN_HILOGI("SensorPowerTest_005 in"); + SensorUser user; + user.callback = SensorDataCallbackImpl; + ClientInfoCallback callback = ClientInfoCallbackImpl; + + int32_t ret = RegisterClientInfoCallback(callback); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + + ret = SubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = SetBatch(sensorId, &user, 100000000, 100000000); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = ActivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + ret = SuspendSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + + ret = ResumeSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + + ret = DeactivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + + ret = UnregisterClientInfoCallback(callback); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + + ret = UnsubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorPowerTest, SensorPowerTest_006, TestSize.Level1) +{ + // 场景用例6,注册回调函数1》注册回调函数2》订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》取消订阅ACC传感器》取消注册回调函数1》取消注册回调函数2 + SEN_HILOGI("SensorPowerTest_006 in"); + SensorUser user; + user.callback = SensorDataCallbackImpl; + ClientInfoCallback callback = ClientInfoCallbackImpl; + ClientInfoCallback callback2 = ClientInfoCallbackImpl2; + + int32_t ret = RegisterClientInfoCallback(callback); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = RegisterClientInfoCallback(callback2); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + + ret = SubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = SetBatch(sensorId, &user, 100000000, 100000000); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = ActivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + ret = SuspendSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + + ret = ResumeSensors(process_pid); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + + ret = DeactivateSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = UnsubscribeSensor(sensorId, &user); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + + ret = UnregisterClientInfoCallback(callback); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = UnregisterClientInfoCallback(callback2); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/plugin/BUILD.gn b/interfaces/plugin/BUILD.gn index d8445259..cd864d86 100644 --- a/interfaces/plugin/BUILD.gn +++ b/interfaces/plugin/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -21,7 +21,7 @@ ohos_shared_library("libsensor") { "//third_party/libuv/include", "//commonlibrary/c_utils/base/include", "./include", - "//base/sensors/sensor/utils/include", + "//base/sensors/sensor/utils/common/include", "//foundation/arkui/napi/interfaces/inner_api/napi", ] defines = [ diff --git a/services/sensor/BUILD.gn b/services/sensor/BUILD.gn index de3715a3..24c33870 100644 --- a/services/sensor/BUILD.gn +++ b/services/sensor/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -29,6 +29,8 @@ ohos_shared_library("libsensor_service") { "src/sensor_manager.cpp", "src/sensor_service.cpp", "src/sensor_service_stub.cpp", + "src/stream_server.cpp", + "src/sensor_suspend_policy.cpp", ] include_dirs = [ @@ -37,7 +39,8 @@ ohos_shared_library("libsensor_service") { "$SUBSYSTEM_DIR/sensor/interfaces/native/include", "//commonlibrary/c_utils/base/include", "//utils/system/safwk/native/include", - "$SUBSYSTEM_DIR/sensor/utils/include", + "$SUBSYSTEM_DIR/sensor/utils/common/include", + "$SUBSYSTEM_DIR/sensor/utils/ipc/include", "$SUBSYSTEM_DIR/sensor/services/sensor/include", "//drivers/peripheral/sensor/interfaces/include", "hdi_connection/interface/include", @@ -45,7 +48,10 @@ ohos_shared_library("libsensor_service") { "hdi_connection/hardware/include", ] - deps = [ "$SUBSYSTEM_DIR/sensor/utils:libsensor_utils" ] + deps = [ + "$SUBSYSTEM_DIR/sensor/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/sensor/utils/ipc:libsensor_ipc", + ] external_deps = [ "access_token:libaccesstoken_sdk", diff --git a/services/sensor/include/client_info.h b/services/sensor/include/client_info.h index 558e8c22..dd4167be 100644 --- a/services/sensor/include/client_info.h +++ b/services/sensor/include/client_info.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include "refbase.h" @@ -75,6 +76,11 @@ public: int32_t GetUidByPid(int32_t pid); AccessTokenID GetTokenIdByPid(int32_t pid); + int32_t AddClientInfoCallbackPid(int32_t pid); + int32_t DelClientInfoCallbackPid(int32_t pid); + std::unordered_set GetClientInfoCallbackPidSet(); + bool IsUnregisterClientDeathRecipient(int32_t pid); + private: DISALLOW_COPY_AND_MOVE(ClientInfo); std::vector GetCmdList(int32_t sensorId, int32_t uid); @@ -92,6 +98,9 @@ private: std::map, int32_t> clientPidMap_; std::unordered_map>> cmdMap_; std::unordered_map> dumpQueue_; + + std::mutex clientInfoCallbackMutex_; + std::unordered_set clientInfoCallbackPidSet_; }; } // namespace Sensors } // namespace OHOS diff --git a/services/sensor/include/sensor_service.h b/services/sensor/include/sensor_service.h index e77d05ed..da3cf223 100644 --- a/services/sensor/include/sensor_service.h +++ b/services/sensor/include/sensor_service.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -29,6 +29,8 @@ #include "sensor_hdi_connection.h" #include "sensor_manager.h" #include "sensor_service_stub.h" +#include "sensor_suspend_policy.h" +#include "stream_server.h" namespace OHOS { namespace Sensors { @@ -37,7 +39,7 @@ enum class SensorServiceState { STATE_RUNNING, }; -class SensorService : public SystemAbility, public SensorServiceStub { +class SensorService : public SystemAbility, public StreamServer, public SensorServiceStub { DECLARE_SYSTEM_ABILITY(SensorService) public: @@ -54,6 +56,13 @@ public: const sptr &sensorClient) override; ErrCode DestroySensorChannel(sptr sensorClient) override; void ProcessDeathObserver(const wptr &object); + ErrCode SuspendSensors(int32_t pid) override; + ErrCode ResumeSensors(int32_t pid) override; + ErrCode GetAppSensorList(int32_t pid, std::vector &appSensorList) override; + ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) override; + ErrCode DestroySocketChannel(const sptr &sensorClient) override; + ErrCode EnableClientInfoCallback() override; + ErrCode DisableClientInfoCallback() override; private: DISALLOW_COPY_AND_MOVE(SensorService); @@ -76,12 +85,16 @@ private: ClientInfo &clientInfo_ = ClientInfo::GetInstance(); SensorManager &sensorManager_ = SensorManager::GetInstance(); FlushInfoRecord &flushInfo_ = FlushInfoRecord::GetInstance(); + SensorSuspendPolicy &suspendPolicy_ = SensorSuspendPolicy::GetInstance(); sptr sensorDataProcesser_ = nullptr; sptr reportDataCallback_ = nullptr; std::mutex uidLock_; // death recipient of sensor client sptr clientDeathObserver_ = nullptr; ErrCode SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + + std::atomic_bool IsReportClientInfo_ = false; + void ReportClientInfo(int32_t sensorId, bool isActive, int32_t pid); }; } // namespace Sensors } // namespace OHOS diff --git a/services/sensor/include/sensor_service_stub.h b/services/sensor/include/sensor_service_stub.h index 9259e793..d2830b2a 100644 --- a/services/sensor/include/sensor_service_stub.h +++ b/services/sensor/include/sensor_service_stub.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -39,6 +39,13 @@ private: ErrCode GetAllSensorsInner(MessageParcel &data, MessageParcel &reply); ErrCode CreateDataChannelInner(MessageParcel &data, MessageParcel &reply); ErrCode DestroyDataChannelInner(MessageParcel &data, MessageParcel &reply); + ErrCode SuspendSensorsInner(MessageParcel &data, MessageParcel &reply); + ErrCode ResumeSensorsInner(MessageParcel &data, MessageParcel &reply); + ErrCode GetAppSensorListInner(MessageParcel &data, MessageParcel &reply); + ErrCode CreateSocketChannelInner(MessageParcel &data, MessageParcel &reply); + ErrCode DestroySocketChannelInner(MessageParcel &data, MessageParcel &reply); + ErrCode EnableClientInfoCallbackInner(MessageParcel &data, MessageParcel &reply); + ErrCode DisableClientInfoCallbackInner(MessageParcel &data, MessageParcel &reply); std::unordered_map baseFuncs_; }; } // namespace Sensors diff --git a/services/sensor/include/sensor_suspend_policy.h b/services/sensor/include/sensor_suspend_policy.h new file mode 100644 index 00000000..ea9cca34 --- /dev/null +++ b/services/sensor/include/sensor_suspend_policy.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_SUSPEND_POLICY_H +#define SENSOR_SUSPEND_POLICY_H + +#include +#include +#include + +#include "nocopyable.h" + +#include "app_sensor.h" +#include "client_info.h" +#include "sensor_agent_type.h" +#include "sensor_hdi_connection.h" +#include "sensor_manager.h" +#include "sensors_errors.h" +#include "stream_session.h" + +namespace OHOS { +namespace Sensors { +class SensorSuspendPolicy : public Singleton{ +public: + ErrCode DoSuspend(int32_t pid); + ErrCode DoResume(int32_t pid); + ErrCode GetAppSensorList(int32_t pid, std::vector &appSensorList); + void ReportClientInfo(int32_t pid, const SensorStatus sensorStatus, + const std::vector &sessionList); + +private: + bool CheckFreezingSensor(int32_t sensorId); + bool DisableSensorList(std::unordered_map &SensorInfoMap, + std::vector &sensorIdList, int32_t pid); + ErrCode DisableSensor(std::unordered_map &SensorInfoMap, + int32_t sensorId, int32_t pid); + ErrCode EnableSensor(int32_t sensorId, int32_t pid, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + ErrCode RestoreSensorInfo(int32_t sensorId, int32_t pid, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + SensorHdiConnection &sensorHdiConnection_ = SensorHdiConnection::GetInstance(); + ClientInfo &clientInfo_ = ClientInfo::GetInstance(); + SensorManager &sensorManager_ = SensorManager::GetInstance(); + std::mutex pidSensorInfoMutex_; + std::unordered_map> pidSensorInfoMap_; +}; +} // namespace Sensors +} // namespace OHOS +#endif // SENSOR_SUSPEND_POLICY_H \ No newline at end of file diff --git a/services/sensor/include/stream_server.h b/services/sensor/include/stream_server.h new file mode 100644 index 00000000..32d3c590 --- /dev/null +++ b/services/sensor/include/stream_server.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STREAM_SERVER_H +#define STREAM_SERVER_H + +#include +#include + +#include "nocopyable.h" +#include "refbase.h" + +#include "stream_session.h" +#include "stream_socket.h" + +namespace OHOS { +namespace Sensors { +class StreamServer : public RefBase, public StreamSocket { +public: + StreamServer() = default; + virtual ~StreamServer(); + bool SendMsg(int32_t fd, NetPacket& pkt); + void Multicast(const std::vector& fdList, NetPacket& pkt); + int32_t GetClientFd(int32_t pid); + int32_t GetClientPid(int32_t fd); + SessionPtr GetSession(int32_t fd); + SessionPtr GetSessionByPid(int32_t pid); + int32_t AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenType, int32_t &serverFd, int32_t &clientFd); + DISALLOW_COPY_AND_MOVE(StreamServer); + +protected: + bool AddSession(SessionPtr ses); + void DelSession(int32_t pid); + std::mutex idxPidMutex_; + std::map idxPidMap_; + std::mutex sessionMutex_; + std::map sessionsMap_; +}; +} // namespace Sensors +} // namespace OHOS +#endif // STREAM_SERVER_H diff --git a/services/sensor/src/client_info.cpp b/services/sensor/src/client_info.cpp index 8396fd43..d081932d 100644 --- a/services/sensor/src/client_info.cpp +++ b/services/sensor/src/client_info.cpp @@ -684,5 +684,50 @@ void ClientInfo::ClearDataQueue(int32_t sensorId) dumpQueue_.erase(it); } } + +int32_t ClientInfo::AddClientInfoCallbackPid(int32_t pid) +{ + std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); + auto pairRet = clientInfoCallbackPidSet_.insert(pid); + if (!pairRet.second) { + SEN_HILOGE("ClientInfoCallbackPidSet_ insert pid fail, pid:%{public}d", pid); + return ERROR; + } + return ERR_OK; +} + +int32_t ClientInfo::DelClientInfoCallbackPid(int32_t pid) +{ + std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); + auto it = clientInfoCallbackPidSet_.find(pid); + if (it == clientInfoCallbackPidSet_.end()) { + SEN_HILOGE("ClientInfoCallbackPidSet_ not find pid, pid:%{public}d", pid); + return ERROR; + } + clientInfoCallbackPidSet_.erase(it); + return ERR_OK; +} + +std::unordered_set ClientInfo::GetClientInfoCallbackPidSet() +{ + return clientInfoCallbackPidSet_; +} + +bool ClientInfo::IsUnregisterClientDeathRecipient(int32_t pid) +{ + std::lock_guard channelLock(channelMutex_); + auto channelIt = channelMap_.find(pid); + if (channelIt != channelMap_.end()) { + SEN_HILOGI("pid exist in channelMap, pid:%{public}d", pid); + return false; + } + std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); + auto pidIt = clientInfoCallbackPidSet_.find(pid); + if (pidIt != clientInfoCallbackPidSet_.end()) { + SEN_HILOGI("pid exist in clientInfoCallbackPidSet, pid:%{public}d", pid); + return false; + } + return true; +} } // namespace Sensors } // namespace OHOS diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 2c7563b7..5e03ce19 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,6 +20,7 @@ #include #include +#include "accesstoken_kit.h" #include "hisysevent.h" #include "iservice_registry.h" #include "permission_util.h" @@ -32,7 +33,7 @@ namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; - +using namespace Security::AccessToken; namespace { constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SensorService" }; constexpr int32_t INVALID_SENSOR_ID = -1; @@ -233,6 +234,9 @@ ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, SEN_HILOGE("ret : %{public}d", ret); } ReportOnChangeData(sensorId); + if (IsReportClientInfo_) { + ReportClientInfo(sensorId, true, pid); + } return ERR_OK; } auto ret = SaveSubscriber(sensorId, samplingPeriodNs, maxReportDelayNs); @@ -248,6 +252,9 @@ ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, return ENABLE_SENSOR_ERR; } ReportSensorSysEvent(sensorId, true, pid); + if (IsReportClientInfo_) { + ReportClientInfo(sensorId, true, pid); + } return ret; } @@ -266,6 +273,9 @@ ErrCode SensorService::DisableSensor(int32_t sensorId, int32_t pid) std::lock_guard serviceLock(serviceLock_); if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { SEN_HILOGW("other client is using this sensor now, cannot disable"); + if (IsReportClientInfo_) { + ReportClientInfo(sensorId, false, pid); + } return ERR_OK; } if (sensorHdiConnection_.DisableSensor(sensorId) != ERR_OK) { @@ -275,6 +285,9 @@ ErrCode SensorService::DisableSensor(int32_t sensorId, int32_t pid) int32_t uid = clientInfo_.GetUidByPid(pid); clientInfo_.DestroyCmd(uid); clientInfo_.ClearDataQueue(sensorId); + if (IsReportClientInfo_) { + ReportClientInfo(sensorId, false, pid); + } return sensorManager_.AfterDisableSensor(sensorId); } @@ -357,6 +370,8 @@ void SensorService::ProcessDeathObserver(const wptr &object) SEN_HILOGE("disablesensor failed, ret:%{public}d", ret); } } + DelSession(pid); + clientInfo_.DelClientInfoCallbackPid(pid); clientInfo_.DestroySensorChannel(pid); clientInfo_.DestroyClientPid(client); clientInfo_.DestroyCmd(clientInfo_.GetUidByPid(pid)); @@ -375,6 +390,15 @@ void SensorService::RegisterClientDeathRecipient(sptr sensorClien void SensorService::UnregisterClientDeathRecipient(sptr sensorClient) { CALL_LOG_ENTER; + int32_t pid = clientInfo_.FindClientPid(sensorClient); + if (pid == INVALID_PID) { + SEN_HILOGE("pid is -1"); + return; + } + if (!clientInfo_.IsUnregisterClientDeathRecipient(pid)) { + SEN_HILOGI("Client call other service, not need unregister client death recipient, pid:%{public}d", pid); + return; + } sptr client = iface_cast(sensorClient); clientDeathObserver_ = new (std::nothrow) DeathRecipientTemplate(*const_cast(this)); CHKPV(clientDeathObserver_); @@ -404,5 +428,109 @@ int32_t SensorService::Dump(int32_t fd, const std::vector &args) sensorDump.ParseCommand(fd, argList, sensors_, clientInfo_); return ERR_OK; } + +ErrCode SensorService::SuspendSensors(int32_t pid) +{ + CALL_LOG_ENTER; + if (pid < 0) { + SEN_HILOGE("Pid is invalid, pid:%{public}d", pid); + return CLIENT_PID_INVALID_ERR; + } + int32_t ret = suspendPolicy_.DoSuspend(pid); + if (ret != ERR_OK) { + SEN_HILOGE("Suspend pid sensors failed, pid:%{public}d", pid); + return ERROR; + } + return ERR_OK; +} + +ErrCode SensorService::ResumeSensors(int32_t pid) +{ + CALL_LOG_ENTER; + if (pid < 0) { + SEN_HILOGE("Pid is invalid, pid:%{public}d", pid); + return CLIENT_PID_INVALID_ERR; + } + int32_t ret = suspendPolicy_.DoResume(pid); + if (ret != ERR_OK) { + SEN_HILOGE("Resume pid sensors failed, pid:%{public}d", pid); + return ERROR; + } + return ERR_OK; +} + +ErrCode SensorService::GetAppSensorList(int32_t pid, std::vector &appSensorList) +{ + CALL_LOG_ENTER; + if (pid < 0) { + SEN_HILOGE("Pid is invalid, pid:%{public}d", pid); + return CLIENT_PID_INVALID_ERR; + } + int32_t ret = suspendPolicy_.GetAppSensorList(pid, appSensorList); + if (ret != ERR_OK) { + SEN_HILOGE("Get pid sensor list failed, pid:%{public}d", pid); + return ERROR; + } + return ERR_OK; +} + +ErrCode SensorService::CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) +{ + CALL_LOG_ENTER; + int32_t uid = GetCallingUid(); + int32_t pid = GetCallingPid(); + int32_t tokenType = AccessTokenKit::GetTokenTypeFlag(GetCallingTokenID()); + int32_t serverFd = -1; + clientFd = -1; + int32_t ret = AddSocketPairInfo(uid, pid, tokenType, serverFd, std::ref(clientFd)); + if (ret != ERR_OK) { + SEN_HILOGE("AddSocketPairInfo failed"); + return ERROR; + } + RegisterClientDeathRecipient(sensorClient, pid); + return ERR_OK; +} + +ErrCode SensorService::DestroySocketChannel(const sptr &sensorClient) +{ + CALL_LOG_ENTER; + int32_t pid = GetCallingPid(); + DelSession(pid); + UnregisterClientDeathRecipient(sensorClient); + return ERR_OK; +} + +ErrCode SensorService::EnableClientInfoCallback() +{ + CALL_LOG_ENTER; + IsReportClientInfo_ = true; + int32_t pid = GetCallingPid(); + return clientInfo_.AddClientInfoCallbackPid(pid); +} + +ErrCode SensorService::DisableClientInfoCallback() +{ + CALL_LOG_ENTER; + IsReportClientInfo_ = false; + int32_t pid = GetCallingPid(); + return clientInfo_.DelClientInfoCallbackPid(pid); +} + +void SensorService::ReportClientInfo(int32_t sensorId, bool isActive, int32_t pid) +{ + CALL_LOG_ENTER; + std::vector sessionList; + auto pidSet = clientInfo_.GetClientInfoCallbackPidSet(); + for (auto pid : pidSet) { + auto sess = GetSessionByPid(pid); + if (sess != nullptr) { + sessionList.push_back(sess); + } + } + SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); + SensorStatus sensorStatus(sensorId, isActive, sensorInfo.GetSamplingPeriodNs(), + sensorInfo.GetMaxReportDelayNs()); + suspendPolicy_.ReportClientInfo(pid, sensorStatus, sessionList); +} } // namespace Sensors } // namespace OHOS diff --git a/services/sensor/src/sensor_service_stub.cpp b/services/sensor/src/sensor_service_stub.cpp index 94c2a8af..1c07334d 100755 --- a/services/sensor/src/sensor_service_stub.cpp +++ b/services/sensor/src/sensor_service_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -30,7 +30,6 @@ namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; - namespace { constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SensorServiceStub" }; } // namespace @@ -43,6 +42,13 @@ SensorServiceStub::SensorServiceStub() baseFuncs_[GET_SENSOR_LIST] = &SensorServiceStub::GetAllSensorsInner; baseFuncs_[TRANSFER_DATA_CHANNEL] = &SensorServiceStub::CreateDataChannelInner; baseFuncs_[DESTROY_SENSOR_CHANNEL] = &SensorServiceStub::DestroyDataChannelInner; + baseFuncs_[SUSPEND_SENSORS] = &SensorServiceStub::SuspendSensorsInner; + baseFuncs_[RESUME_SENSORS] = &SensorServiceStub::ResumeSensorsInner; + baseFuncs_[GET_APP_SENSOR_LIST] = &SensorServiceStub::GetAppSensorListInner; + baseFuncs_[CREATE_SOCKET_CHANNEL] = &SensorServiceStub::CreateSocketChannelInner; + baseFuncs_[DESTROY_SOCKET_CHANNEL] = &SensorServiceStub::DestroySocketChannelInner; + baseFuncs_[ENABLE_CLIENT_INFO_CALLBACK] = &SensorServiceStub::EnableClientInfoCallbackInner; + baseFuncs_[DISABLE_CLIENT_INFO_CALLBACK] = &SensorServiceStub::DisableClientInfoCallbackInner; } SensorServiceStub::~SensorServiceStub() @@ -153,5 +159,116 @@ ErrCode SensorServiceStub::DestroyDataChannelInner(MessageParcel &data, MessageP CHKPR(sensorClient, OBJECT_NULL); return DestroySensorChannel(sensorClient); } + +ErrCode SensorServiceStub::SuspendSensorsInner(MessageParcel &data, MessageParcel &reply) +{ + PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); + if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { + SEN_HILOGE("TokenType is not TOKEN_NATIVE"); + return PERMISSION_DENIED; + } + (void)reply; + int32_t pid; + if (!data.ReadInt32(pid)) { + SEN_HILOGE("Parcel read failed"); + return ERROR; + } + return SuspendSensors(pid); +} + +ErrCode SensorServiceStub::ResumeSensorsInner(MessageParcel &data, MessageParcel &reply) +{ + PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); + if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { + SEN_HILOGE("TokenType is not TOKEN_NATIVE"); + return PERMISSION_DENIED; + } + (void)reply; + int32_t pid; + if (!data.ReadInt32(pid)) { + SEN_HILOGE("Parcel read failed"); + return ERROR; + } + return ResumeSensors(pid); +} + +ErrCode SensorServiceStub::GetAppSensorListInner(MessageParcel &data, MessageParcel &reply) +{ + PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); + if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { + SEN_HILOGE("TokenType is not TOKEN_NATIVE"); + return PERMISSION_DENIED; + } + int32_t pid; + if (!data.ReadInt32(pid)) { + SEN_HILOGE("Parcel read failed"); + return ERROR; + } + std::vector appSensors; + GetAppSensorList(pid, appSensors); + int32_t appSensorCount = int32_t { appSensors.size() }; + reply.WriteInt32(appSensorCount); + for (int32_t i = 0; i < appSensorCount; i++) { + if (!appSensors[i].Marshalling(reply)) { + SEN_HILOGE("AppSensor %{public}d failed", i); + return ERROR; + } + } + return NO_ERROR; +} + +ErrCode SensorServiceStub::CreateSocketChannelInner(MessageParcel &data, MessageParcel &reply) +{ + sptr sensorClient = data.ReadRemoteObject(); + CHKPR(sensorClient, OBJECT_NULL); + int32_t clientFd = -1; + int32_t ret = CreateSocketChannel(clientFd, sensorClient); + if (ret != ERR_OK) { + SEN_HILOGE("Create socket channel failed"); + if (clientFd >= 0) { + close(clientFd); + } + return ret; + } + if (!reply.WriteFileDescriptor(clientFd)) { + SEN_HILOGE("Write file descriptor failed"); + close(clientFd); + return ERROR; + } + close(clientFd); + return ERR_OK; +} + +ErrCode SensorServiceStub::DestroySocketChannelInner(MessageParcel &data, MessageParcel &reply) +{ + sptr sensorClient = data.ReadRemoteObject(); + CHKPR(sensorClient, OBJECT_NULL); + int32_t ret = DestroySocketChannel(sensorClient); + if (ret != ERR_OK) { + SEN_HILOGE("DestroySocketChannel failed"); + return ret; + } + return ERR_OK; +} + +ErrCode SensorServiceStub::EnableClientInfoCallbackInner(MessageParcel &data, MessageParcel &reply) +{ + PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); + if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { + SEN_HILOGE("TokenType is not TOKEN_NATIVE"); + return PERMISSION_DENIED; + } + return EnableClientInfoCallback(); +} + +ErrCode SensorServiceStub::DisableClientInfoCallbackInner(MessageParcel &data, MessageParcel &reply) +{ + PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); + if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { + SEN_HILOGE("TokenType is not TOKEN_NATIVE"); + return PERMISSION_DENIED; + } + return DisableClientInfoCallback(); +} } // namespace Sensors } // namespace OHOS diff --git a/services/sensor/src/sensor_suspend_policy.cpp b/services/sensor/src/sensor_suspend_policy.cpp index 82ac9832..8176953a 100644 --- a/services/sensor/src/sensor_suspend_policy.cpp +++ b/services/sensor/src/sensor_suspend_policy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,9 +16,6 @@ #include "sensor_suspend_policy.h" #include "sensor.h" -#include "sensor_agent_type.h" -#include "sensor_service.h" -#include "system_ability_definition.h" namespace OHOS { namespace Sensors { @@ -28,73 +25,119 @@ namespace { constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SensorSuspendPolicy" }; constexpr int32_t INVALID_SENSOR_ID = -1; constexpr int64_t MAX_EVENT_COUNT = 1000; -constexpr int64_t DEFAULT_SAMPLING_RATE = 200000000; -constexpr int64_t DEFAULT_REPORT_DELAY = 0; } // namespace -SensorSuspendPolicy::~SensorSuspendPolicy() -{} - bool SensorSuspendPolicy::CheckFreezingSensor(int32_t sensorId) { return ((sensorId == SENSOR_TYPE_ID_PEDOMETER_DETECTION) || (sensorId == SENSOR_TYPE_ID_PEDOMETER)); } -ErrCode SensorSuspendPolicy::DisableSensor(int32_t sensorId, int32_t pid) +ErrCode SensorSuspendPolicy::DoSuspend(int32_t pid) { CALL_LOG_ENTER; - if (sensorId == INVALID_SENSOR_ID) { - SEN_HILOGE("sensorId is invalid"); - return ERR_NO_INIT; + std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); + std::lock_guard pidSensorInfoLock(pidSensorInfoMutex_); + auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); + if (pidSensorInfoIt != pidSensorInfoMap_.end()) { + if (sensorIdList.empty()) { + SEN_HILOGI("Pid already suspend, all sensors suspend success, not need suspend again, pid: %{public}d", pid); + return ERR_OK; + } else { + SEN_HILOGI("Pid already suspend, some sensors suspend failed, suspend these sensors again, pid: %{public}d", pid); + std::unordered_map SensorInfoMap = pidSensorInfoIt->second; + if (!DisableSensorList(SensorInfoMap, sensorIdList, pid)) { + SEN_HILOGE("Some sensor disable failed"); + return DISABLE_SENSOR_ERR; + } + return ERR_OK; + } } - if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { - SEN_HILOGW("other client is using this sensor now, cannot disable"); - return ERR_OK; + if (sensorIdList.empty()) { + SEN_HILOGE("Pid sensorId list is empty, pid: %{public}d", pid); + return ERROR; } - if (interface_.DisableSensor(sensorId) != ERR_OK) { - SEN_HILOGE("DisableSensor is failed"); + std::unordered_map SensorInfoMap; + bool suspendAllSensors = DisableSensorList(SensorInfoMap, sensorIdList, pid); + pidSensorInfoMap_.insert(std::make_pair(pid, SensorInfoMap)); + if (!suspendAllSensors) { + SEN_HILOGE("Some sensor disable failed"); return DISABLE_SENSOR_ERR; } - return sensorManager_.AfterDisableSensor(sensorId); + return ERR_OK; } -void SensorSuspendPolicy::DoSuspend(const std::shared_ptr &info) +bool SensorSuspendPolicy::DisableSensorList(std::unordered_map &SensorInfoMap, + std::vector &sensorIdList, int32_t pid) { CALL_LOG_ENTER; - std::lock_guard suspendLock(suspendMutex_); - auto &list = info->GetAppIPCInfoList(); - for (const auto &appInfo : list) { - std::vector sensorIdList = clientInfo_.GetSensorIdByPid(appInfo.pid); - if (sensorIdList.empty()) { + bool suspendAllSensors = true; + for (auto &sensorId : sensorIdList) { + if (CheckFreezingSensor(sensorId)) { continue; } - pidSensorIdMap_.emplace(std::make_pair(appInfo.pid, sensorIdList)); - for (auto &sensorId : sensorIdList) { - if (CheckFreezingSensor(sensorId)) { - continue; - } - auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, appInfo.pid); - sensorIdInfoMap_.emplace(std::make_pair(sensorId, sensorInfo)); - DisableSensor(sensorId, appInfo.pid); + auto ret = DisableSensor(SensorInfoMap, sensorId, pid); + if (ret != ERR_OK) { + SEN_HILOGE("Disable Sensor is failed. sensorId: %{public}u, pid: %{public}d, ret: %{public}d", + sensorId, pid, ret); + suspendAllSensors = false; } } + return suspendAllSensors; } -ErrCode SensorSuspendPolicy::SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, - int64_t maxReportDelayNs, int32_t pid) +ErrCode SensorSuspendPolicy::DisableSensor(std::unordered_map &SensorInfoMap, + int32_t sensorId, int32_t pid) { - auto ret = sensorManager_.SaveSubscriber(sensorId, pid, samplingPeriodNs, maxReportDelayNs); - if (ret != ERR_OK) { - SEN_HILOGE("SaveSubscriber is failed"); - return ret; + CALL_LOG_ENTER; + if (sensorId == INVALID_SENSOR_ID) { + SEN_HILOGE("SensorId is invalid"); + return ERR_NO_INIT; } - sensorManager_.StartDataReportThread(); - if (!sensorManager_.SetBestSensorParams(sensorId, samplingPeriodNs, maxReportDelayNs)) { - SEN_HILOGE("SetBestSensorParams is failed"); - clientInfo_.RemoveSubscriber(sensorId, pid); + auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); + if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { + SEN_HILOGW("Other client is using this sensor now, cannot disable"); + SensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); + return ERR_OK; + } + if (sensorHdiConnection_.DisableSensor(sensorId) != ERR_OK) { + SEN_HILOGE("DisableSensor is failed"); + return DISABLE_SENSOR_ERR; + } + SensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); + return sensorManager_.AfterDisableSensor(sensorId); +} + +ErrCode SensorSuspendPolicy::DoResume(int32_t pid) +{ + CALL_LOG_ENTER; + std::lock_guard pidSensorInfoLock(pidSensorInfoMutex_); + auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); + if (pidSensorInfoIt == pidSensorInfoMap_.end()) { + SEN_HILOGE("Pid not have suspend sensors, pid: %{public}d", pid); + return ERROR; + } + bool resumeAllSensors = true; + std::unordered_map SensorInfoMap = pidSensorInfoIt->second; + for (auto sensorIt = SensorInfoMap.begin(); sensorIt != SensorInfoMap.end();) { + int32_t sensorId = sensorIt->first; + int64_t samplingPeriodNs = sensorIt->second.GetSamplingPeriodNs(); + int64_t maxReportDelayNs = sensorIt->second.GetMaxReportDelayNs(); + auto ret = EnableSensor(sensorId, pid, samplingPeriodNs, maxReportDelayNs); + if (ret != ERR_OK) { + SEN_HILOGE("Enable Sensor is failed. sensorId: %{public}u, pid: %{public}d, ret: %{public}d", + sensorId, pid, ret); + resumeAllSensors = false; + ++sensorIt; + } else { + sensorIt = SensorInfoMap.erase(sensorIt); + } + } + if (!resumeAllSensors) { + SEN_HILOGE("Some sensor enable failed"); return ENABLE_SENSOR_ERR; } - return ret; + pidSensorInfoMap_.erase(pidSensorInfoIt); + return ERR_OK; } ErrCode SensorSuspendPolicy::EnableSensor(int32_t sensorId, int32_t pid, int64_t samplingPeriodNs, @@ -103,76 +146,94 @@ ErrCode SensorSuspendPolicy::EnableSensor(int32_t sensorId, int32_t pid, int64_t CALL_LOG_ENTER; if ((sensorId == INVALID_SENSOR_ID) || (samplingPeriodNs == 0) || ((samplingPeriodNs != 0L) && (maxReportDelayNs / samplingPeriodNs > MAX_EVENT_COUNT))) { - SEN_HILOGE("sensorId is 0 or maxReportDelayNs exceed the maximum value"); + SEN_HILOGE("SensorId is 0 or maxReportDelayNs exceed the maximum value"); return ERR_NO_INIT; } - if (clientInfo_.GetSensorState(sensorId) == SENSOR_ENABLED) { - SEN_HILOGW("sensor has been enabled already"); - auto ret = SaveSubscriber(sensorId, samplingPeriodNs, maxReportDelayNs, pid); + if (clientInfo_.GetSensorState(sensorId)) { + SEN_HILOGW("Sensor has been enabled already, sensorId: %{public}d", sensorId); + auto ret = RestoreSensorInfo(sensorId, pid, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { - SEN_HILOGE("SaveSubscriber is failed"); + SEN_HILOGE("RestoreSensorInfo is failed, ret: %{public}d", ret); return ret; } - uint32_t flag = sensorManager_.GetSensorFlag(sensorId); - ret = flushInfo_.FlushProcess(sensorId, flag, pid, true); if (ret != ERR_OK) { - SEN_HILOGW("ret:%{public}d", ret); + SEN_HILOGE("FlushProcess is failed, ret: %{public}d", ret); } return ERR_OK; } - auto ret = SaveSubscriber(sensorId, samplingPeriodNs, maxReportDelayNs, pid); + auto ret = RestoreSensorInfo(sensorId, pid, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { - SEN_HILOGE("SaveSubscriber is failed"); + SEN_HILOGE("RestoreSensorInfo is failed, ret: %{public}d", ret); return ret; } - ret = interface_.EnableSensor(sensorId); + ret = sensorHdiConnection_.EnableSensor(sensorId); + if (ret != ERR_OK) { + SEN_HILOGE("EnableSensor is failed, ret: %{public}d", ret); + clientInfo_.RemoveSubscriber(sensorId, pid); + return ENABLE_SENSOR_ERR; + } + return ERR_OK; +} + +ErrCode SensorSuspendPolicy::RestoreSensorInfo(int32_t sensorId, int32_t pid, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) +{ + auto ret = sensorManager_.SaveSubscriber(sensorId, pid, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { - SEN_HILOGE("EnableSensor is failed"); + SEN_HILOGE("RestoreSensorInfo is failed, ret: %{public}d", ret); + return ret; + } + sensorManager_.StartDataReportThread(); + if (!sensorManager_.SetBestSensorParams(sensorId, samplingPeriodNs, maxReportDelayNs)) { + SEN_HILOGE("SetBestSensorParams is failed"); clientInfo_.RemoveSubscriber(sensorId, pid); return ENABLE_SENSOR_ERR; } return ret; } -std::vector SensorSuspendPolicy::GetSensorIdByPid(int32_t pid) +ErrCode SensorSuspendPolicy::GetAppSensorList(int32_t pid, std::vector &appSensorList) { - SEN_HILOGD("pid:%{public}d", pid); - auto it = pidSensorIdMap_.find(pid); - if (it != pidSensorIdMap_.end()) { - SEN_HILOGD("pid:%{public}d found", pid); - return it->second; - } - SEN_HILOGD("pid:%{public}d not found", pid); - return {}; + CALL_LOG_ENTER; + std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); + for (auto &sensorId : sensorIdList) { + auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); + SensorStatus sensorStatus(sensorId, true, sensorInfo.GetSamplingPeriodNs(), + sensorInfo.GetMaxReportDelayNs()); + AppSensor appSensor(pid, sensorStatus); + appSensorList.push_back(appSensor); + } + std::lock_guard pidSensorInfoLock(pidSensorInfoMutex_); + auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); + if (pidSensorInfoIt != pidSensorInfoMap_.end()) { + std::unordered_map SensorInfoMap = pidSensorInfoIt->second; + for (auto &sensorInfo : SensorInfoMap) { + SensorStatus sensorStatus(sensorInfo.first, false, sensorInfo.second.GetSamplingPeriodNs(), + sensorInfo.second.GetMaxReportDelayNs()); + AppSensor appSensor(pid, sensorStatus); + appSensorList.push_back(appSensor); + } + } + return ERR_OK; } -void SensorSuspendPolicy::DoActive(const std::shared_ptr &info) +void SensorSuspendPolicy::ReportClientInfo(int32_t pid, const SensorStatus sensorStatus, + const std::vector &sessionList) { CALL_LOG_ENTER; - int64_t samplePeriod = DEFAULT_SAMPLING_RATE; - int64_t maxReportDelay = DEFAULT_REPORT_DELAY; - std::vector sensorIdList; - std::lock_guard suspendLock(suspendMutex_); - auto &list = info->GetAppIPCInfoList(); - for (const auto &appInfo : list) { - sensorIdList = GetSensorIdByPid(appInfo.pid); - for (auto &sensorId : sensorIdList) { - if (CheckFreezingSensor(sensorId)) { - continue; - } - auto it = sensorIdInfoMap_.find(sensorId); - if (it != sensorIdInfoMap_.end()) { - samplePeriod = it->second.GetSamplingPeriodNs(); - maxReportDelay = it->second.GetMaxReportDelayNs(); - } - auto ret = EnableSensor(sensorId, appInfo.pid, samplePeriod, maxReportDelay); - if (ret != ERR_OK) { - SEN_HILOGE("sensorId:%{public}u,pid:%{public}d,ret:%{public}d", sensorId, appInfo.pid, ret); - } + NetPacket pkt(MessageId::CLIENT_INFO); + pkt << pid << sensorStatus.sensorId << sensorStatus.isActive << sensorStatus.samplingPeriodNs << + sensorStatus.maxReportDelayNs; + if (pkt.ChkRWError()) { + SEN_HILOGE("Packet write data failed"); + return; + } + for (auto sess : sessionList) { + if (!sess->SendMsg(pkt)) { + SEN_HILOGE("Packet send failed, pid:%{public}d", sess->GetPid()); + continue; } } - pidSensorIdMap_.clear(); - sensorIdInfoMap_.clear(); } } // namespace Sensors -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp new file mode 100644 index 00000000..a93b676f --- /dev/null +++ b/services/sensor/src/stream_server.cpp @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stream_server.h" + +#include +#include + +#include "accesstoken_kit.h" + +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { +namespace { +using namespace Security::AccessToken; +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "StreamServer" }; +constexpr int32_t INVALID_PID = -1; +constexpr int32_t INVALID_FD = -1; +} // namespace +StreamServer::~StreamServer() +{ + CALL_LOG_ENTER; + idxPidMap_.clear(); + for (const auto &item : sessionsMap_) { + item.second->Close(); + } + sessionsMap_.clear(); +} + +bool StreamServer::SendMsg(int32_t fd, NetPacket& pkt) +{ + CALL_LOG_ENTER; + if (fd < 0) { + SEN_HILOGE("The fd is less than 0"); + return false; + } + auto ses = GetSession(fd); + if (ses == nullptr) { + SEN_HILOGE("The fd:%{public}d not found, The message was discarded. errCode:%{public}d", + fd, PROTO_SESSION_NOT_FOUND); + return false; + } + return ses->SendMsg(pkt); +} + +void StreamServer::Multicast(const std::vector& fdList, NetPacket& pkt) +{ + CALL_LOG_ENTER; + for (const auto &item : fdList) { + SendMsg(item, pkt); + } +} + +int32_t StreamServer::GetClientFd(int32_t pid) +{ + std::lock_guard idxPidLock(idxPidMutex_); + auto it = idxPidMap_.find(pid); + if (it == idxPidMap_.end()) { + return INVALID_FD; + } + return it->second; +} + +int32_t StreamServer::GetClientPid(int32_t fd) +{ + std::lock_guard sessionLock(sessionMutex_); + auto it = sessionsMap_.find(fd); + if (it == sessionsMap_.end()) { + return INVALID_PID; + } + return it->second->GetPid(); +} + +SessionPtr StreamServer::GetSession(int32_t fd) +{ + std::lock_guard sessionLock(sessionMutex_); + auto it = sessionsMap_.find(fd); + if (it == sessionsMap_.end()) { + SEN_HILOGE("Session not found.fd:%{public}d", fd); + return nullptr; + } + CHKPP(it->second); + return it->second->GetSharedPtr(); +} + +SessionPtr StreamServer::GetSessionByPid(int32_t pid) +{ + int32_t fd = GetClientFd(pid); + if (fd <= 0) { + SEN_HILOGE("Session not found.pid:%{public}d", pid); + return nullptr; + } + return GetSession(fd); +} + +int32_t StreamServer::AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenType, + int32_t &serverFd, int32_t &clientFd) +{ + CALL_LOG_ENTER; + std::string programName = ""; + int32_t moduleType = 0; + int32_t sockFds[2] = { -1 }; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockFds) != 0) { + SEN_HILOGE("Call socketpair failed, errno:%{public}d", errno); + return ERROR; + } + serverFd = sockFds[0]; + clientFd = sockFds[1]; + if (serverFd < 0 || clientFd < 0) { + SEN_HILOGE("Call fcntl failed, errno:%{public}d", errno); + return ERROR; + } + static constexpr size_t bufferSize = 32 * 1024; + static constexpr size_t nativeBufferSize = 64 * 1024; + SessionPtr sess = nullptr; + if (setsockopt(serverFd, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)) != 0) { + SEN_HILOGE("Setsockopt serverFd failed, errno: %{public}d", errno); + goto CLOSE_SOCK; + } + if (setsockopt(serverFd, SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize)) != 0) { + SEN_HILOGE("Setsockopt serverFd failed, errno: %{public}d", errno); + goto CLOSE_SOCK; + } + if (tokenType == ATokenTypeEnum::TOKEN_NATIVE) { + if (setsockopt(clientFd, SOL_SOCKET, SO_SNDBUF, &nativeBufferSize, sizeof(nativeBufferSize)) != 0) { + SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); + goto CLOSE_SOCK; + } + if (setsockopt(clientFd, SOL_SOCKET, SO_RCVBUF, &nativeBufferSize, sizeof(nativeBufferSize)) != 0) { + SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); + goto CLOSE_SOCK; + } + } else { + if (setsockopt(clientFd, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)) != 0) { + SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); + goto CLOSE_SOCK; + } + if (setsockopt(clientFd, SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize)) != 0) { + SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); + goto CLOSE_SOCK; + } + } + sess = std::make_shared(programName, moduleType, serverFd, uid, pid); + sess->SetTokenType(tokenType); + if (!AddSession(sess)) { + SEN_HILOGE("AddSession fail errCode:%{public}d", PROTO_ADD_SESSION_FAIL); + goto CLOSE_SOCK; + } + return ERR_OK; + +CLOSE_SOCK: + close(serverFd); + serverFd = -1; + close(clientFd); + clientFd = -1; + return ERROR; +} + +bool StreamServer::AddSession(SessionPtr ses) +{ + CALL_LOG_ENTER; + CHKPF(ses); + auto fd = ses->GetFd(); + if (fd < 0) { + SEN_HILOGE("The fd is less than 0"); + return false; + } + auto pid = ses->GetPid(); + if (pid <= 0) { + SEN_HILOGE("Get process failed"); + return false; + } + if (sessionsMap_.size() > PROTO_MAX_SESSON_ALARM) { + SEN_HILOGE("Too many clients. Warning Value:%{public}d, Current Value:%{public}zd", + PROTO_MAX_SESSON_ALARM, sessionsMap_.size()); + return false; + } + + DelSession(pid); + std::lock_guard idxPidLock(idxPidMutex_); + idxPidMap_[pid] = fd; + std::lock_guard sessionLock(sessionMutex_); + sessionsMap_[fd] = ses; + + SEN_HILOGI("************AddSession()************"); + SEN_HILOGI("******idxPidMap_ size is %{public}zu******", idxPidMap_.size()); + for (auto it = idxPidMap_.begin(); it != idxPidMap_.end(); it++) { + SEN_HILOGI("******pid:%{public}d, fd:%{public}d******", it->first, it->second); + } + SEN_HILOGI("******sessionsMap_ size is %{public}zu******", sessionsMap_.size()); + for (auto it = sessionsMap_.begin(); it != sessionsMap_.end(); it++) { + SEN_HILOGI("******fd:%{public}d, programName:%{public}s, moduleType:%{public}d, fd:%{public}d, uid:%{public}d, pid:%{public}d", + it->first, it->second->GetProgramName().c_str(), it->second->GetModuleType(), it->second->GetFd(), it->second->GetUid(), it->second->GetPid()); + } + return true; +} + +void StreamServer::DelSession(int32_t pid) +{ + CALL_LOG_ENTER; + std::lock_guard idxPidLock(idxPidMutex_); + auto pidIt = idxPidMap_.find(pid); + if (pidIt == idxPidMap_.end()) { + return; + } + int32_t fd = pidIt->second; + idxPidMap_.erase(pidIt); + std::lock_guard sessionLock(sessionMutex_); + auto fdIt = sessionsMap_.find(fd); + if (fdIt != sessionsMap_.end()) { + sessionsMap_.erase(fdIt); + } + if (fd >= 0) { + auto rf = close(fd); + if (rf > 0) { + SEN_HILOGE("Socket fd close failed, fd:%{public}d, rf:%{public}d", fd, rf); + } + } + + SEN_HILOGI("************DelSession()************"); + SEN_HILOGI("******idxPidMap_ size is %{public}zu******", idxPidMap_.size()); + for (auto it = idxPidMap_.begin(); it != idxPidMap_.end(); it++) { + SEN_HILOGI("******pid:%{public}d, fd:%{public}d******", it->first, it->second); + } + SEN_HILOGI("******sessionsMap_ size is %{public}zu******", sessionsMap_.size()); + for (auto it = sessionsMap_.begin(); it != sessionsMap_.end(); it++) { + SEN_HILOGI("******fd:%{public}d, programName:%{public}s, moduleType:%{public}d, fd:%{public}d, uid:%{public}d, pid:%{public}d", + it->first, it->second->GetProgramName().c_str(), it->second->GetModuleType(), it->second->GetFd(), it->second->GetUid(), it->second->GetPid()); + } +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/common/include/system_info.h b/test/unittest/common/include/system_info.h index b48b8fda..76ad756a 100644 --- a/test/unittest/common/include/system_info.h +++ b/test/unittest/common/include/system_info.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -36,6 +36,7 @@ class CpuInfo : public SystemInfo { public: double GetSystemCpuUsage(); double GetProcCpuUsage(const std::string& process_name); + int32_t GetTaskPidFile(const std::string& process_name); private: struct Total_Cpu_Occupy { char name[20] { 0 }; @@ -56,7 +57,6 @@ private: int32_t cutime { 0 }; int32_t cstime { 0 }; }; - int32_t GetTaskPidFile(const std::string& process_name); int32_t GetProcOccupy(int32_t pid); int32_t GetSystemCpuStatInfo(Total_Cpu_Occupy& info); diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 7a971bb7..80796c29 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -11,38 +11,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/ohos.gni") -SUBSYSTEM_DIR = "//base/sensors" -ohos_shared_library("libsensor_utils") { - sources = [ - "src/permission_util.cpp", - "src/report_data_callback.cpp", - "src/sensor.cpp", - "src/sensor_basic_data_channel.cpp", - "src/sensor_basic_info.cpp", - "src/sensor_channel_info.cpp", - ] - - include_dirs = [ - "include", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", - "//drivers/peripheral/sensor/interfaces/include", - "$SUBSYSTEM_DIR/sensor/interfaces/native/include", - ] - - external_deps = [ - "access_token:libaccesstoken_sdk", - "access_token:libprivacy_sdk", - "c_utils:utils", - "hisysevent_native:libhisysevent", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - ] - part_name = "sensor" - subsystem_name = "sensors" -} - group("sensor_utils_target") { - deps = [ ":libsensor_utils" ] + deps = [ + "common:libsensor_utils", + "ipc:libsensor_ipc", + ] } diff --git a/utils/common/BUILD.gn b/utils/common/BUILD.gn new file mode 100644 index 00000000..c5b02656 --- /dev/null +++ b/utils/common/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +SUBSYSTEM_DIR = "//base/sensors" + +ohos_shared_library("libsensor_utils") { + sources = [ + "src/app_sensor.cpp", + "src/permission_util.cpp", + "src/report_data_callback.cpp", + "src/sensor.cpp", + "src/sensor_basic_data_channel.cpp", + "src/sensor_basic_info.cpp", + "src/sensor_channel_info.cpp", + ] + + include_dirs = [ + "include", + "//commonlibrary/c_utils/base/include", + "//utils/system/safwk/native/include", + "//drivers/peripheral/sensor/interfaces/include", + "$SUBSYSTEM_DIR/sensor/interfaces/native/include", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libprivacy_sdk", + "c_utils:utils", + "hisysevent_native:libhisysevent", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + part_name = "sensor" + subsystem_name = "sensors" +} diff --git a/utils/common/include/app_sensor.h b/utils/common/include/app_sensor.h new file mode 100644 index 00000000..18558e94 --- /dev/null +++ b/utils/common/include/app_sensor.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APP_SENSOR_H +#define APP_SENSOR_H + +#include "parcel.h" + +namespace OHOS { +namespace Sensors { +struct SensorStatus { + int32_t sensorId {-1}; + bool isActive {false}; + int64_t samplingPeriodNs {-1}; + int64_t maxReportDelayNs {-1}; + SensorStatus() {} + SensorStatus(int32_t sensorId, bool isActive, int64_t samplingPeriodNs, int64_t maxReportDelayNs) + : sensorId(sensorId), isActive(isActive), samplingPeriodNs(samplingPeriodNs), + maxReportDelayNs(maxReportDelayNs) {} +}; + +class AppSensor : public Parcelable { +public: + AppSensor() = default; + AppSensor(int32_t pid, SensorStatus sensorStatus); + virtual ~AppSensor() = default; + int32_t GetPid() const; + void SetPid(int32_t pid); + int32_t GetSensorId() const; + void SetSensorId(int32_t sensorId); + bool IsActive() const; + void Enable(bool isActive); + int64_t GetSamplingPeriodNs() const; + void SetSamplingPeriodNs(int64_t samplingPeriodNs); + int64_t GetMaxReportDelayNs() const; + void SetMaxReportDelayNs(int64_t maxReportDelayNs); + bool Marshalling(Parcel &parcel) const; + std::unique_ptr Unmarshalling(Parcel &parcel); + +private: + int32_t pid_ {-1}; + int32_t sensorId_ {-1}; + bool isActive_ {-1}; + int64_t samplingPeriodNs_ {-1}; + int64_t maxReportDelayNs_ {-1}; +}; +} // namespace Sensors +} // namespace OHOS +#endif // APP_SENSOR_H \ No newline at end of file diff --git a/utils/include/app_thread_info.h b/utils/common/include/app_thread_info.h similarity index 100% rename from utils/include/app_thread_info.h rename to utils/common/include/app_thread_info.h diff --git a/utils/include/death_recipient_template.h b/utils/common/include/death_recipient_template.h similarity index 100% rename from utils/include/death_recipient_template.h rename to utils/common/include/death_recipient_template.h diff --git a/utils/include/miscdevice_common.h b/utils/common/include/miscdevice_common.h similarity index 100% rename from utils/include/miscdevice_common.h rename to utils/common/include/miscdevice_common.h diff --git a/utils/include/permission_util.h b/utils/common/include/permission_util.h similarity index 96% rename from utils/include/permission_util.h rename to utils/common/include/permission_util.h index ba61b2f8..dadbacbd 100644 --- a/utils/include/permission_util.h +++ b/utils/common/include/permission_util.h @@ -30,6 +30,7 @@ public: PermissionUtil() = default; virtual ~PermissionUtil() {}; int32_t CheckSensorPermission(AccessTokenID callerToken, int32_t sensorTypeId); + bool IsNativeToken(AccessTokenID tokenID); private: void AddPermissionRecord(AccessTokenID tokenID, const std::string& permissionName, bool status); diff --git a/utils/include/report_data_callback.h b/utils/common/include/report_data_callback.h similarity index 100% rename from utils/include/report_data_callback.h rename to utils/common/include/report_data_callback.h diff --git a/utils/include/sensor.h b/utils/common/include/sensor.h similarity index 100% rename from utils/include/sensor.h rename to utils/common/include/sensor.h diff --git a/utils/include/sensor_basic_data_channel.h b/utils/common/include/sensor_basic_data_channel.h similarity index 100% rename from utils/include/sensor_basic_data_channel.h rename to utils/common/include/sensor_basic_data_channel.h diff --git a/utils/include/sensor_basic_info.h b/utils/common/include/sensor_basic_info.h similarity index 100% rename from utils/include/sensor_basic_info.h rename to utils/common/include/sensor_basic_info.h diff --git a/utils/include/sensor_channel_info.h b/utils/common/include/sensor_channel_info.h similarity index 100% rename from utils/include/sensor_channel_info.h rename to utils/common/include/sensor_channel_info.h diff --git a/utils/include/sensor_data_event.h b/utils/common/include/sensor_data_event.h similarity index 100% rename from utils/include/sensor_data_event.h rename to utils/common/include/sensor_data_event.h diff --git a/utils/include/sensor_log.h b/utils/common/include/sensor_log.h similarity index 100% rename from utils/include/sensor_log.h rename to utils/common/include/sensor_log.h diff --git a/utils/include/sensors_errors.h b/utils/common/include/sensors_errors.h similarity index 99% rename from utils/include/sensors_errors.h rename to utils/common/include/sensors_errors.h index 55e11c3c..35335518 100644 --- a/utils/include/sensors_errors.h +++ b/utils/common/include/sensors_errors.h @@ -88,7 +88,8 @@ enum { REGIST_PERMISSION_CHANGED_ERR = COPY_ERR + 1, DUMP_PARAM_ERR = REGIST_PERMISSION_CHANGED_ERR + 1, WRITE_MSG_ERR = DUMP_PARAM_ERR + 1, - SET_SENSOR_MODE_ERR = WRITE_MSG_ERR + 1, + READ_MSG_ERR = WRITE_MSG_ERR + 1, + SET_SENSOR_MODE_ERR = READ_MSG_ERR + 1, SET_SENSOR_OPTION_ERR = SET_SENSOR_MODE_ERR + 1, REGIST_CALLBACK_ERR = SET_SENSOR_OPTION_ERR + 1, }; diff --git a/utils/common/src/app_sensor.cpp b/utils/common/src/app_sensor.cpp new file mode 100644 index 00000000..18668359 --- /dev/null +++ b/utils/common/src/app_sensor.cpp @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_sensor.h" + +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { +using namespace OHOS::HiviewDFX; +namespace { +constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "AppSensor" }; +} + +AppSensor::AppSensor(int32_t pid, SensorStatus sensorStatus) +{ + pid_ = pid; + sensorId_ = sensorStatus.sensorId; + isActive_ = sensorStatus.isActive; + samplingPeriodNs_ = sensorStatus.samplingPeriodNs; + maxReportDelayNs_ = sensorStatus.maxReportDelayNs; +} + +int32_t AppSensor::GetPid() const +{ + return pid_; +} + +void AppSensor::SetPid(int32_t pid) +{ + pid_ = pid; +} + +int32_t AppSensor::GetSensorId() const +{ + return sensorId_; +} + +void AppSensor::SetSensorId(int32_t sensorId) +{ + sensorId_ = sensorId; +} + +bool AppSensor::IsActive() const +{ + return isActive_; +} + +void AppSensor::Enable(bool isActive) +{ + isActive_ = isActive; +} + +int64_t AppSensor::GetSamplingPeriodNs() const +{ + return samplingPeriodNs_; +} + +void AppSensor::SetSamplingPeriodNs(int64_t samplingPeriodNs) +{ + samplingPeriodNs_ = samplingPeriodNs; +} + +int64_t AppSensor::GetMaxReportDelayNs() const +{ + return maxReportDelayNs_; +} + +void AppSensor::SetMaxReportDelayNs(int64_t maxReportDelayNs) +{ + maxReportDelayNs_ = maxReportDelayNs; +} + +bool AppSensor::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(pid_)) { + SEN_HILOGE("Write pid failed"); + return false; + } + if (!parcel.WriteInt32(sensorId_)) { + SEN_HILOGE("Write sensorId failed"); + return false; + } + if (!parcel.WriteBool(isActive_)) { + SEN_HILOGE("Write isActive failed"); + return false; + } + if (!parcel.WriteInt64(samplingPeriodNs_)) { + SEN_HILOGE("Write samplingPeriodNs failed"); + return false; + } + if (!parcel.WriteInt64(maxReportDelayNs_)) { + SEN_HILOGE("Write maxReportDelayNs failed"); + return false; + } + return true; +} + +std::unique_ptr AppSensor::Unmarshalling(Parcel &parcel) +{ + int32_t pid = -1; + int32_t sensorId = -1; + bool isActive = false; + int64_t samplingPeriodNs = -1; + int64_t maxReportDelayNs = -1; + if (!(parcel.ReadInt32(pid) && parcel.ReadInt32(sensorId) && parcel.ReadBool(isActive) && + parcel.ReadInt64(samplingPeriodNs) && parcel.ReadInt64(maxReportDelayNs))) { + SEN_HILOGE("ReadFromParcel is failed"); + return nullptr; + } + auto appSensor = std::make_unique(); + appSensor->SetPid(pid); + appSensor->SetSensorId(sensorId); + appSensor->Enable(isActive); + appSensor->SetSamplingPeriodNs(samplingPeriodNs); + appSensor->SetMaxReportDelayNs(maxReportDelayNs); + return appSensor; +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/utils/src/permission_util.cpp b/utils/common/src/permission_util.cpp similarity index 90% rename from utils/src/permission_util.cpp rename to utils/common/src/permission_util.cpp index 4e2d91e0..9e5bd305 100644 --- a/utils/src/permission_util.cpp +++ b/utils/common/src/permission_util.cpp @@ -67,5 +67,15 @@ void PermissionUtil::AddPermissionRecord(AccessTokenID tokenID, const std::strin permissionName.c_str(), successCount, failCount); } } + +bool PermissionUtil::IsNativeToken(AccessTokenID tokenID) +{ + int32_t tokenType = AccessTokenKit::GetTokenTypeFlag(tokenID); + if (tokenType != ATokenTypeEnum::TOKEN_NATIVE) { + SEN_HILOGE("TokenType is not TOKEN_NATIVE, tokenType:%{public}d", tokenType); + return false; + } + return true; +} } // namespace Sensors } // namespace OHOS diff --git a/utils/src/report_data_callback.cpp b/utils/common/src/report_data_callback.cpp similarity index 100% rename from utils/src/report_data_callback.cpp rename to utils/common/src/report_data_callback.cpp diff --git a/utils/src/sensor.cpp b/utils/common/src/sensor.cpp similarity index 100% rename from utils/src/sensor.cpp rename to utils/common/src/sensor.cpp diff --git a/utils/src/sensor_basic_data_channel.cpp b/utils/common/src/sensor_basic_data_channel.cpp similarity index 100% rename from utils/src/sensor_basic_data_channel.cpp rename to utils/common/src/sensor_basic_data_channel.cpp diff --git a/utils/src/sensor_basic_info.cpp b/utils/common/src/sensor_basic_info.cpp similarity index 100% rename from utils/src/sensor_basic_info.cpp rename to utils/common/src/sensor_basic_info.cpp diff --git a/utils/src/sensor_channel_info.cpp b/utils/common/src/sensor_channel_info.cpp similarity index 100% rename from utils/src/sensor_channel_info.cpp rename to utils/common/src/sensor_channel_info.cpp diff --git a/utils/ipc/BUILD.gn b/utils/ipc/BUILD.gn new file mode 100644 index 00000000..5986159a --- /dev/null +++ b/utils/ipc/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +SUBSYSTEM_DIR = "//base/sensors" + +ohos_shared_library("libsensor_ipc") { + sources = [ + "src/circle_stream_buffer.cpp", + "src/net_packet.cpp", + "src/stream_buffer.cpp", + "src/stream_client.cpp", + "src/stream_session.cpp", + "src/stream_socket.cpp", + ] + + include_dirs = [ + "include", + "//commonlibrary/c_utils/base/include", + "//utils/system/safwk/native/include", + "//drivers/peripheral/sensor/interfaces/include", + "$SUBSYSTEM_DIR/sensor/utils/common/include", + ] + + deps = [ "$SUBSYSTEM_DIR/sensor/utils/common:libsensor_utils" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + part_name = "sensor" + subsystem_name = "sensors" +} diff --git a/utils/ipc/include/circle_stream_buffer.h b/utils/ipc/include/circle_stream_buffer.h new file mode 100644 index 00000000..3aaea490 --- /dev/null +++ b/utils/ipc/include/circle_stream_buffer.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CIRCLE_STREAM_BUFFER_H +#define CIRCLE_STREAM_BUFFER_H + +#include "stream_buffer.h" + +namespace OHOS { +namespace Sensors { +class CircleStreamBuffer : public StreamBuffer { + static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "CircleStreamBuffer" }; +public: + CircleStreamBuffer() = default; + virtual ~CircleStreamBuffer() = default; + bool CheckWrite(size_t size); + virtual bool Write(const char *buf, size_t size) override; + DISALLOW_MOVE(CircleStreamBuffer); + +protected: + void CopyDataToBegin(); +}; +} // namespace Sensors +} // namespace OHOS +#endif // CIRCLE_STREAM_BUFFER_H \ No newline at end of file diff --git a/utils/ipc/include/net_packet.h b/utils/ipc/include/net_packet.h new file mode 100644 index 00000000..33d3545e --- /dev/null +++ b/utils/ipc/include/net_packet.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_PACKET_H +#define NET_PACKET_H + +#include "proto.h" +#include "stream_buffer.h" + +#pragma pack(1) +using PACKHEAD = struct PackHead { + OHOS::Sensors::MessageId idMsg; + int32_t size; +}; + +#pragma pack() +namespace OHOS { +namespace Sensors { +class NetPacket : public StreamBuffer { + static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "NetPacket" }; +public: + explicit NetPacket(MessageId msgId); + NetPacket(const NetPacket &pkt); + NetPacket &operator = (const NetPacket &pkt); + virtual ~NetPacket(); + virtual void MakeData(StreamBuffer &buf) const; + size_t GetSize() const; + int32_t GetPacketLength() const; + const char* GetData() const; + MessageId GetMsgId() const; + DISALLOW_MOVE(NetPacket); + +protected: + MessageId msgId_ = MessageId::INVALID; +}; +} // namespace Sensors +} // namespace OHOS +#endif // NET_PACKET_H \ No newline at end of file diff --git a/utils/ipc/include/proto.h b/utils/ipc/include/proto.h new file mode 100644 index 00000000..207b8640 --- /dev/null +++ b/utils/ipc/include/proto.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROTO_H +#define PROTO_H + +#include + +namespace OHOS { +namespace Sensors { +#define PROTO_SEND_RETRY_LIMIT 32 +#define PROTO_SEND_RETRY_SLEEP_TIME 10000 + +static const int32_t PROTO_STREAM_BUF_READ_FAIL = 1; +static const int32_t PROTO_STREAM_BUF_WRITE_FAIL = 2; +static const int32_t PROTO_MEM_OUT_OF_BOUNDS = 3; +static const int32_t PROTO_MEMCPY_SEC_FUN_FAIL = 4; +static const int32_t PROTO_PARAM_INPUT_INVALID = 5; +static const int32_t PROTO_SESSION_NOT_FOUND = 8; +static const int32_t PROTO_MAX_VECTOR_SIZE = 10; +static const int32_t PROTO_ADD_SESSION_FAIL = 11; +static const int32_t PROTO_MAX_SESSON_ALARM = 12; +static const int32_t PROTO_MAX_RECV_LIMIT = 13; + +static const int32_t PROTO_MAX_STREAM_BUF_SIZE = 256; +static const int32_t PROTO_MAX_PACKET_BUF_SIZE = 256; +static const int32_t PROTO_ONCE_PROCESS_NETPACKET_LIMIT = 100; + +enum class MessageId : int32_t { + INVALID, + CLIENT_INFO, +}; +} // namespace Sensors +} // namespace OHOS +#endif // PROTO_H \ No newline at end of file diff --git a/utils/ipc/include/stream_buffer.h b/utils/ipc/include/stream_buffer.h new file mode 100644 index 00000000..0cea6fae --- /dev/null +++ b/utils/ipc/include/stream_buffer.h @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STREAM_BUFFER_H +#define STREAM_BUFFER_H + +#include +#include +#include + +#include "nocopyable.h" +#include "securec.h" + +#include "proto.h" +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { +class StreamBuffer { + static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "StreamBuffer" }; +public: + StreamBuffer() = default; + explicit StreamBuffer(const StreamBuffer &buf); + virtual StreamBuffer &operator=(const StreamBuffer &other); + virtual ~StreamBuffer() = default; + void Reset(); + void Clean(); + bool SeekReadPos(int32_t n); + bool Read(std::string &buf); + bool Read(StreamBuffer &buf); + bool Read(char *buf, size_t size); + bool Write(const std::string &buf); + bool Write(const StreamBuffer &buf); + virtual bool Write(const char *buf, size_t size); + bool IsEmpty() const; + bool ChkRWError() const; + size_t Size() const; + int32_t UnreadSize() const; + int32_t GetAvailableBufSize() const; + const std::string& GetErrorStatusRemark() const; + const char* Data() const; + + template + bool Read(T &data); + template + bool Write(const T &data); + template + bool Read(std::vector &data); + template + bool Write(const std::vector &data); + const char *ReadBuf() const; + const char *WriteBuf() const; + template + StreamBuffer &operator >> (T &data); + template + StreamBuffer &operator << (const T &data); + DISALLOW_MOVE(StreamBuffer); + +protected: + bool Clone(const StreamBuffer &buf); + enum class ErrorStatus { + ERROR_STATUS_OK, + ERROR_STATUS_READ, + ERROR_STATUS_WRITE, + }; + ErrorStatus rwErrorStatus_ = ErrorStatus::ERROR_STATUS_OK; + int32_t rCount_ { 0 }; + int32_t wCount_ { 0 }; + int32_t rPos_ { 0 }; + int32_t wPos_ { 0 }; + char szBuff_[PROTO_MAX_STREAM_BUF_SIZE + 1] = {}; +}; + +template +bool StreamBuffer::Read(T &data) +{ + if (!Read(reinterpret_cast(&data), sizeof(data))) { + SEN_HILOGE("[%{public}s] size:%{public}zu count:%{public}d,errCode:%{public}d", + GetErrorStatusRemark().c_str(), sizeof(data), rCount_ + 1, PROTO_STREAM_BUF_READ_FAIL); + return false; + } + return true; +} + +template +bool StreamBuffer::Write(const T &data) +{ + if (!Write(reinterpret_cast(&data), sizeof(data))) { + SEN_HILOGE("[%{public}s] size:%{public}zu,count:%{public}d,errCode:%{public}d", + GetErrorStatusRemark().c_str(), sizeof(data), wCount_ + 1, PROTO_STREAM_BUF_WRITE_FAIL); + return false; + } + return true; +} + +template +bool StreamBuffer::Read(std::vector &data) +{ + int32_t size = 0; + if (!Read(size)) { + SEN_HILOGE("Read vector size error"); + return false; + } + if (size < 0 || size > PROTO_MAX_VECTOR_SIZE) { + SEN_HILOGE("Read vector size:%{public}d error", size); + return false; + } + for (int32_t i = 0; i < size; i++) { + T val; + if (!Read(val)) { + SEN_HILOGE("Read vector data error"); + return false; + } + data.push_back(val); + } + return true; +} + +template +bool StreamBuffer::Write(const std::vector &data) +{ + if (data.size() > INT32_MAX) { + SEN_HILOGE("Vector exceeds the max range"); + return false; + } + int32_t size = static_cast(data.size()); + if (!Write(size)) { + SEN_HILOGE("Write vector size error"); + return false; + } + for (const auto &item : data) { + if (!Write(item)) { + SEN_HILOGE("Write vector data error"); + return false; + } + } + return true; +} + +template +StreamBuffer &StreamBuffer::operator>>(T &data) +{ + if (!Read(data)) { + SEN_HILOGW("Read data failed"); + } + return *this; +} + +template +StreamBuffer &StreamBuffer::operator<<(const T &data) +{ + if (!Write(data)) { + SEN_HILOGW("Write data failed"); + } + return *this; +} +} // namespace Sensors +} // namespace OHOS +#endif // STREAM_BUFFER_H \ No newline at end of file diff --git a/utils/ipc/include/stream_client.h b/utils/ipc/include/stream_client.h new file mode 100644 index 00000000..4dd9a1e9 --- /dev/null +++ b/utils/ipc/include/stream_client.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STREAM_CLIENT_H +#define STREAM_CLIENT_H + +#include +#include +#include + +#include "nocopyable.h" + +#include "net_packet.h" +#include "stream_socket.h" + +namespace OHOS { +namespace Sensors { +class StreamClient; +using MsgClientFunCallback = std::function; +class StreamClient : public StreamSocket { +public: + StreamClient(); + virtual ~StreamClient(); + virtual int32_t Socket() = 0; + virtual void Stop(); + int32_t ConnectTo(); + bool SendMsg(const char *buf, size_t size) const; + bool SendMsg(const NetPacket &pkt) const; + bool GetConnectedStatus() const; + DISALLOW_COPY_AND_MOVE(StreamClient); + +protected: + virtual void OnConnected() {} + virtual void OnDisconnected() {} + bool StartClient(MsgClientFunCallback fun); + bool isExit { false }; + bool isRunning_ { false }; + bool isConnected_ { false }; + MsgClientFunCallback recvFun_; +}; +} // namespace Sensors +} // namespace OHOS +#endif // STREAM_CLIENT_H \ No newline at end of file diff --git a/utils/ipc/include/stream_session.h b/utils/ipc/include/stream_session.h new file mode 100644 index 00000000..adbf4dc1 --- /dev/null +++ b/utils/ipc/include/stream_session.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STREAM_SESSION_H +#define STREAM_SESSION_H + +#include +#include +#include + +#include +#include + +#include "accesstoken_kit.h" +#include "nocopyable.h" + +#include "net_packet.h" +#include "proto.h" + +namespace OHOS { +namespace Sensors { +class StreamSession; +using SessionPtr = std::shared_ptr; +using namespace Security::AccessToken; +class StreamSession : public std::enable_shared_from_this { +public: + StreamSession(const std::string &programName, const int32_t moduleType, const int32_t fd, const int32_t uid, + const int32_t pid); + virtual ~StreamSession() = default; + bool SendMsg(const char *buf, size_t size) const; + bool SendMsg(NetPacket &pkt) const; + void Close(); + int32_t GetUid() const; + int32_t GetPid() const; + int32_t GetModuleType() const; + SessionPtr GetSharedPtr(); + int32_t GetFd() const; + const std::string& GetDescript() const; + const std::string GetProgramName() const; + void SetTokenType(int32_t type); + int32_t GetTokenType() const; + void UpdateDescript(); + DISALLOW_COPY_AND_MOVE(StreamSession); + +protected: + struct EventTime { + int32_t id { 0 }; + int64_t eventTime { 0 }; + int32_t timerId { -1 }; + }; + std::map> events_; + std::string descript_; + const std::string programName_; + const int32_t moduleType_ { -1 }; + int32_t fd_ { -1 }; + const int32_t uid_ { -1 }; + const int32_t pid_ { -1 }; + int32_t tokenType_ { ATokenTypeEnum::TOKEN_INVALID }; +}; +} // namespace Sensors +} // namespace OHOS +#endif // STREAM_SESSION_H \ No newline at end of file diff --git a/utils/ipc/include/stream_socket.h b/utils/ipc/include/stream_socket.h new file mode 100644 index 00000000..acae2006 --- /dev/null +++ b/utils/ipc/include/stream_socket.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STREAM_SOCKET_H +#define STREAM_SOCKET_H + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "nocopyable.h" + +#include "circle_stream_buffer.h" +#include "net_packet.h" + +namespace OHOS { +namespace Sensors { +class StreamSocket { +public: + using PacketCallBackFun = std::function; + StreamSocket(); + virtual ~StreamSocket(); + int32_t EpollCreate(int32_t size); + int32_t EpollCtl(int32_t fd, int32_t op, struct epoll_event &event, int32_t epollFd = -1); + int32_t EpollWait(struct epoll_event &events, int32_t maxevents, int32_t timeout, int32_t epollFd = -1); + void OnReadPackets(CircleStreamBuffer &buf, PacketCallBackFun callbackFun); + void EpollClose(); + void Close(); + int32_t GetFd() const; + int32_t GetEpollFd() const; + + DISALLOW_COPY_AND_MOVE(StreamSocket); + +protected: + int32_t fd_ { -1 }; + int32_t epollFd_ { -1 }; +}; +} // namespace Sensors +} // namespace OHOS +#endif // STREAM_SOCKET_H \ No newline at end of file diff --git a/utils/ipc/src/circle_stream_buffer.cpp b/utils/ipc/src/circle_stream_buffer.cpp new file mode 100644 index 00000000..a2c91f54 --- /dev/null +++ b/utils/ipc/src/circle_stream_buffer.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "circle_stream_buffer.h" + +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { +bool CircleStreamBuffer::CheckWrite(size_t size) +{ + int32_t bufferSize = static_cast(size); + int32_t availSize = GetAvailableBufSize(); + if (bufferSize > availSize && rPos_ > 0) { + CopyDataToBegin(); + availSize = GetAvailableBufSize(); + } + return (availSize >= bufferSize); +} + +bool CircleStreamBuffer::Write(const char *buf, size_t size) +{ + if (!CheckWrite(size)) { + SEN_HILOGE("Out of buffer memory, availableSize:%{public}d, size:%{public}zu," + "unreadSize:%{public}d, rPos:%{public}d, wPos:%{public}d", + GetAvailableBufSize(), size, UnreadSize(), rPos_, wPos_); + return false; + } + return StreamBuffer::Write(buf, size); +} + +void CircleStreamBuffer::CopyDataToBegin() +{ + int32_t unreadSize = UnreadSize(); + if (unreadSize > 0 && rPos_ > 0) { + int32_t pos = 0; + for (int32_t i = rPos_; i <= wPos_;) { + szBuff_[pos++] = szBuff_[i++]; + } + } + SEN_HILOGD("UnreadSize:%{public}d, rPos:%{public}d, wPos:%{public}d", unreadSize, rPos_, wPos_); + rPos_ = 0; + wPos_ = unreadSize; +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/utils/ipc/src/net_packet.cpp b/utils/ipc/src/net_packet.cpp new file mode 100644 index 00000000..7e3a3bae --- /dev/null +++ b/utils/ipc/src/net_packet.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "net_packet.h" + +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { +NetPacket::NetPacket(MessageId msgId) : msgId_(msgId) {} + +NetPacket::NetPacket(const NetPacket &pkt) : NetPacket(pkt.GetMsgId()) +{ + Clone(pkt); +} + +NetPacket::~NetPacket() {} + +void NetPacket::MakeData(StreamBuffer &buf) const +{ + PACKHEAD head = {msgId_, wPos_}; + buf << head; + if (wPos_ > 0) { + if (!buf.Write(&szBuff_[0], wPos_)) { + SEN_HILOGE("Write data to stream failed, errCode:%{public}d", PROTO_STREAM_BUF_WRITE_FAIL); + return; + } + } +} + +size_t NetPacket::GetSize() const +{ + return Size(); +} + +int32_t NetPacket::GetPacketLength() const +{ + return (static_cast(sizeof(PackHead)) + wPos_); +} + +const char* NetPacket::GetData() const +{ + return Data(); +} + +MessageId NetPacket::GetMsgId() const +{ + return msgId_; +} +} // namespace Sensors +} // namespace OHOS diff --git a/utils/ipc/src/stream_buffer.cpp b/utils/ipc/src/stream_buffer.cpp new file mode 100644 index 00000000..a586ef72 --- /dev/null +++ b/utils/ipc/src/stream_buffer.cpp @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stream_buffer.h" + +#include +#include + +namespace OHOS { +namespace Sensors { +StreamBuffer::StreamBuffer(const StreamBuffer &buf) +{ + Clone(buf); +} + +StreamBuffer &StreamBuffer::operator=(const StreamBuffer &other) +{ + Clone(other); + return *this; +} + +void StreamBuffer::Reset() +{ + rPos_ = 0; + wPos_ = 0; + rCount_ = 0; + wCount_ = 0; + rwErrorStatus_ = ErrorStatus::ERROR_STATUS_OK; +} + +void StreamBuffer::Clean() +{ + Reset(); + errno_t ret = memset_sp(&szBuff_, sizeof(szBuff_), 0, sizeof(szBuff_)); + if (ret != EOK) { + SEN_HILOGE("Call memset_s fail"); + return; + } +} + +bool StreamBuffer::SeekReadPos(int32_t n) +{ + int32_t pos = rPos_ + n; + if (pos < 0 || pos > wPos_) { + SEN_HILOGE("The position in the calculation is not as expected. pos:%{public}d [0, %{public}d]", pos, wPos_); + return false; + } + rPos_ = pos; + return true; +} + +bool StreamBuffer::Read(std::string &buf) +{ + if (rPos_ == wPos_) { + SEN_HILOGE("Not enough memory to read, errCode:%{public}d", PROTO_STREAM_BUF_READ_FAIL); + rwErrorStatus_ = ErrorStatus::ERROR_STATUS_READ; + return false; + } + buf = ReadBuf(); + rPos_ += static_cast(buf.length()) + 1; + return (buf.length() > 0); +} + +bool StreamBuffer::Write(const std::string &buf) +{ + return Write(buf.c_str(), buf.length()+1); +} + +bool StreamBuffer::Read(StreamBuffer &buf) +{ + return buf.Write(Data(), Size()); +} + +bool StreamBuffer::Write(const StreamBuffer &buf) +{ + return Write(buf.Data(), buf.Size()); +} + +bool StreamBuffer::Read(char *buf, size_t size) +{ + if (ChkRWError()) { + return false; + } + if (buf == nullptr) { + SEN_HILOGE("Invalid input parameter buf=nullptr errCode:%{public}d", PROTO_PARAM_INPUT_INVALID); + rwErrorStatus_ = ErrorStatus::ERROR_STATUS_READ; + return false; + } + if (size == 0) { + SEN_HILOGE("Invalid input parameter size=%{public}zu errCode:%{public}d", size, PROTO_PARAM_INPUT_INVALID); + rwErrorStatus_ = ErrorStatus::ERROR_STATUS_READ; + return false; + } + if (rPos_ + static_cast(size) > wPos_) { + SEN_HILOGE("Memory out of bounds on read... errCode:%{public}d", PROTO_MEM_OUT_OF_BOUNDS); + rwErrorStatus_ = ErrorStatus::ERROR_STATUS_READ; + return false; + } + errno_t ret = memcpy_sp(buf, size, ReadBuf(), size); + if (ret != EOK) { + SEN_HILOGE("Failed to call memcpy_sp. errCode:%{public}d", PROTO_MEMCPY_SEC_FUN_FAIL); + rwErrorStatus_ = ErrorStatus::ERROR_STATUS_READ; + return false; + } + rPos_ += static_cast(size); + rCount_ += 1; + return true; +} + +bool StreamBuffer::Write(const char *buf, size_t size) +{ + if (ChkRWError()) { + return false; + } + if (buf == nullptr) { + SEN_HILOGE("Invalid input parameter buf=nullptr errCode:%{public}d", PROTO_PARAM_INPUT_INVALID); + rwErrorStatus_ = ErrorStatus::ERROR_STATUS_WRITE; + return false; + } + if (size == 0) { + SEN_HILOGE("Invalid input parameter size=%{public}zu errCode:%{public}d", size, PROTO_PARAM_INPUT_INVALID); + rwErrorStatus_ = ErrorStatus::ERROR_STATUS_WRITE; + return false; + } + if (wPos_ + static_cast(size) > PROTO_MAX_STREAM_BUF_SIZE) { + SEN_HILOGE("The write length exceeds buffer. wIdx:%{public}d size:%{public}zu maxBufSize:%{public}d" + "errCode:%{public}d", wPos_, size, PROTO_MAX_STREAM_BUF_SIZE, PROTO_MEM_OUT_OF_BOUNDS); + rwErrorStatus_ = ErrorStatus::ERROR_STATUS_WRITE; + return false; + } + errno_t ret = memcpy_sp(&szBuff_[wPos_], GetAvailableBufSize(), buf, size); + if (ret != EOK) { + SEN_HILOGE("Failed to call memcpy_sp. errCode:%{public}d", PROTO_MEMCPY_SEC_FUN_FAIL); + rwErrorStatus_ = ErrorStatus::ERROR_STATUS_WRITE; + return false; + } + wPos_ += static_cast(size); + wCount_ += 1; + return true; +} + +bool StreamBuffer::IsEmpty() const +{ + return (rPos_ == wPos_); +} + +size_t StreamBuffer::Size() const +{ + return static_cast(wPos_); +} + +int32_t StreamBuffer::UnreadSize() const +{ + return ((wPos_ <= rPos_) ? 0 : (wPos_ - rPos_)); +} + +int32_t StreamBuffer::GetAvailableBufSize() const +{ + return ((wPos_ >= PROTO_MAX_STREAM_BUF_SIZE) ? 0 : (PROTO_MAX_STREAM_BUF_SIZE - wPos_)); +} + +bool StreamBuffer::ChkRWError() const +{ + return (rwErrorStatus_ != ErrorStatus::ERROR_STATUS_OK); +} + +const std::string &StreamBuffer::GetErrorStatusRemark() const +{ + static const std::vector> remark { + {ErrorStatus::ERROR_STATUS_OK, "OK"}, + {ErrorStatus::ERROR_STATUS_READ, "READ_ERROR"}, + {ErrorStatus::ERROR_STATUS_WRITE, "WRITE_ERROR"}, + }; + static const std::string invalidStatus { "UNKNOWN" }; + + auto tIter = std::find_if(remark.cbegin(), remark.cend(), + [this](const auto &item) { + return (item.first == rwErrorStatus_); + } + ); + return (tIter != remark.cend() ? tIter->second : invalidStatus); +} + +const char *StreamBuffer::Data() const +{ + return &szBuff_[0]; +} + +const char *StreamBuffer::ReadBuf() const +{ + return &szBuff_[rPos_]; +} + +const char *StreamBuffer::WriteBuf() const +{ + return &szBuff_[wPos_]; +} + +bool StreamBuffer::Clone(const StreamBuffer &buf) +{ + Clean(); + return Write(buf.Data(), buf.Size()); +} +} // namespace Sensors +} // namespace OHOS diff --git a/utils/ipc/src/stream_client.cpp b/utils/ipc/src/stream_client.cpp new file mode 100644 index 00000000..4e1fedf9 --- /dev/null +++ b/utils/ipc/src/stream_client.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stream_client.h" + +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "StreamClient" }; +} + +StreamClient::StreamClient() {} + +StreamClient::~StreamClient() {} + +int32_t StreamClient::ConnectTo() +{ + CALL_LOG_ENTER; + if (Socket() < 0) { + SEN_HILOGE("Socket failed"); + return ERROR; + } + OnConnected(); + return SUCCESS; +} + +bool StreamClient::SendMsg(const char *buf, size_t size) const +{ + CALL_LOG_ENTER; + CHKPF(buf); + if ((size == 0) || (size > PROTO_MAX_PACKET_BUF_SIZE)) { + SEN_HILOGE("Stream buffer size out of range"); + return false; + } + if (fd_ < 0) { + SEN_HILOGE("The fd_ is less than 0"); + return false; + } + int32_t idx = 0; + int32_t retryCount = 0; + const int32_t bufSize = static_cast(size); + int32_t remSize = bufSize; + while (remSize > 0 && retryCount < PROTO_SEND_RETRY_LIMIT) { + retryCount += 1; + auto count = send(fd_, &buf[idx], remSize, MSG_DONTWAIT | MSG_NOSIGNAL); + if (count < 0) { + if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) { + SEN_HILOGW("Continue for errno EAGAIN|EINTR|EWOULDBLOCK, errno:%{public}d", errno); + continue; + } + SEN_HILOGE("Send return failed,error:%{public}d fd:%{public}d", errno, fd_); + return false; + } + idx += count; + remSize -= count; + if (remSize > 0) { + usleep(PROTO_SEND_RETRY_SLEEP_TIME); + } + } + if (retryCount >= PROTO_SEND_RETRY_LIMIT || remSize != 0) { + SEN_HILOGE("Send too many times:%{public}d/%{public}d,size:%{public}d/%{public}d fd:%{public}d", + retryCount, PROTO_SEND_RETRY_LIMIT, idx, bufSize, fd_); + return false; + } + return true; +} + +bool StreamClient::SendMsg(const NetPacket &pkt) const +{ + CALL_LOG_ENTER; + if (pkt.ChkRWError()) { + SEN_HILOGE("Read and write status is error"); + return false; + } + StreamBuffer buf; + pkt.MakeData(buf); + return SendMsg(buf.Data(), buf.Size()); +} + +bool StreamClient::StartClient(MsgClientFunCallback fun) +{ + CALL_LOG_ENTER; + if (isRunning_ || isConnected_) { + SEN_HILOGE("Client is connected or started"); + return false; + } + isExit = false; + recvFun_ = fun; + if (ConnectTo() < 0) { + SEN_HILOGW("Client connection failed, Try again later"); + } + return true; +} + +void StreamClient::Stop() +{ + CALL_LOG_ENTER; + isExit = true; + isRunning_ = false; + Close(); +} + +bool StreamClient::GetConnectedStatus() const +{ + return isConnected_; +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/utils/ipc/src/stream_session.cpp b/utils/ipc/src/stream_session.cpp new file mode 100644 index 00000000..dd837974 --- /dev/null +++ b/utils/ipc/src/stream_session.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stream_session.h" + +#include +#include + +#include +#include +#include +#include + +#include "proto.h" +#include "stream_socket.h" +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "StreamSession" }; +} + +StreamSession::StreamSession(const std::string &programName, const int32_t moduleType, const int32_t fd, + const int32_t uid, const int32_t pid) + : programName_(programName), + moduleType_(moduleType), + fd_(fd), + uid_(uid), + pid_(pid) +{ + UpdateDescript(); +} + +bool StreamSession::SendMsg(const char *buf, size_t size) const +{ + CHKPF(buf); + if ((size == 0) || (size > PROTO_MAX_PACKET_BUF_SIZE)) { + SEN_HILOGE("Buf size:%{public}zu", size); + return false; + } + if (fd_ < 0) { + SEN_HILOGE("The fd_ is less than 0"); + return false; + } + + int32_t idx = 0; + int32_t retryCount = 0; + const int32_t bufSize = static_cast(size); + int32_t remSize = bufSize; + while (remSize > 0 && retryCount < PROTO_SEND_RETRY_LIMIT) { + retryCount += 1; + auto count = send(fd_, &buf[idx], remSize, MSG_DONTWAIT | MSG_NOSIGNAL); + if (count < 0) { + if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) { + usleep(PROTO_SEND_RETRY_SLEEP_TIME); + SEN_HILOGW("Continue for errno EAGAIN|EINTR|EWOULDBLOCK, errno:%{public}d", errno); + continue; + } + SEN_HILOGE("Send return failed,error:%{public}d fd:%{public}d", errno, fd_); + return false; + } + idx += count; + remSize -= count; + if (remSize > 0) { + usleep(PROTO_SEND_RETRY_SLEEP_TIME); + } + } + if (retryCount >= PROTO_SEND_RETRY_LIMIT || remSize != 0) { + SEN_HILOGE("Send too many times:%{public}d/%{public}d,size:%{public}d/%{public}d fd:%{public}d", + retryCount, PROTO_SEND_RETRY_LIMIT, idx, bufSize, fd_); + return false; + } + return true; +} + +void StreamSession::Close() +{ + SEN_HILOGD("Enter fd_:%{public}d.", fd_); + if (fd_ >= 0) { + close(fd_); + fd_ = -1; + UpdateDescript(); + } +} + +void StreamSession::UpdateDescript() +{ + std::ostringstream oss; + oss << "fd = " << fd_ + << ", programName = " << programName_ + << ", moduleType = " << moduleType_ + << ((fd_ < 0) ? ", closed" : ", opened") + << ", uid = " << uid_ + << ", pid = " << pid_ + << ", tokenType = " << tokenType_ + << std::endl; + descript_ = oss.str().c_str(); +} + +bool StreamSession::SendMsg(NetPacket &pkt) const +{ + if (pkt.ChkRWError()) { + SEN_HILOGE("Read and write status is error"); + return false; + } + StreamBuffer buf; + pkt.MakeData(buf); + return SendMsg(buf.Data(), buf.Size()); +} + +int32_t StreamSession::GetUid() const +{ + return uid_; +} + +int32_t StreamSession::GetPid() const +{ + return pid_; +} + +int32_t StreamSession::GetModuleType() const +{ + return moduleType_; +} + +SessionPtr StreamSession::GetSharedPtr() +{ + return shared_from_this(); +} + +int32_t StreamSession::GetFd() const +{ + return fd_; +} + +const std::string& StreamSession::GetDescript() const +{ + return descript_; +} + +const std::string StreamSession::GetProgramName() const +{ + return programName_; +} + +void StreamSession::SetTokenType(int32_t type) +{ + tokenType_ = type; +} + +int32_t StreamSession::GetTokenType() const +{ + return tokenType_; +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/utils/ipc/src/stream_socket.cpp b/utils/ipc/src/stream_socket.cpp new file mode 100644 index 00000000..1a2044df --- /dev/null +++ b/utils/ipc/src/stream_socket.cpp @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stream_socket.h" + +#include + +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "StreamSocket" }; +} // namespace + +StreamSocket::StreamSocket() {} + +StreamSocket::~StreamSocket() +{ + Close(); + EpollClose(); +} + +int32_t StreamSocket::EpollCreate(int32_t size) +{ + epollFd_ = epoll_create(size); + if (epollFd_ < 0) { + SEN_HILOGE("Epoll_create return %{public}d", epollFd_); + } else { + SEN_HILOGI("Epoll_create, epollFd_:%{public}d", epollFd_); + } + return epollFd_; +} + +int32_t StreamSocket::EpollCtl(int32_t fd, int32_t op, struct epoll_event &event, int32_t epollFd) +{ + if (fd < 0) { + SEN_HILOGE("Invalid fd"); + return ERROR; + } + if (epollFd < 0) { + epollFd = epollFd_; + } + if (epollFd < 0) { + SEN_HILOGE("Invalid param epollFd"); + return ERROR; + } + int32_t ret; + if (op == EPOLL_CTL_DEL) { + ret = epoll_ctl(epollFd, op, fd, NULL); + } else { + ret = epoll_ctl(epollFd, op, fd, &event); + } + if (ret < 0) { + SEN_HILOGE("Epoll_ctl return %{public}d,epollFd_:%{public}d, op:%{public}d,fd:%{public}d,errno:%{public}d", + ret, epollFd, op, fd, errno); + } + return ret; +} + +int32_t StreamSocket::EpollWait(struct epoll_event &events, int32_t maxevents, int32_t timeout, int32_t epollFd) +{ + if (epollFd < 0) { + epollFd = epollFd_; + } + if (epollFd < 0) { + SEN_HILOGE("Invalid param epollFd"); + return ERROR; + } + auto ret = epoll_wait(epollFd, &events, maxevents, timeout); + if (ret < 0) { + SEN_HILOGE("Epoll_wait ret:%{public}d,errno:%{public}d", ret, errno); + } + return ret; +} + +void StreamSocket::OnReadPackets(CircleStreamBuffer &circBuf, StreamSocket::PacketCallBackFun callbackFun) +{ + constexpr int32_t headSize = static_cast(sizeof(PackHead)); + for (int32_t i = 0; i < PROTO_ONCE_PROCESS_NETPACKET_LIMIT; i++) { + const int32_t unreadSize = circBuf.UnreadSize(); + if (unreadSize < headSize) { + break; + } + int32_t dataSize = unreadSize - headSize; + char *buf = const_cast(circBuf.ReadBuf()); + CHKPB(buf); + PackHead *head = reinterpret_cast(buf); + CHKPB(head); + if (head->size < 0 || head->size > PROTO_MAX_PACKET_BUF_SIZE) { + SEN_HILOGE("Packet header parsing error, and this error cannot be recovered. The buffer will be reset." + " head->size:%{public}d, unreadSize:%{public}d", head->size, unreadSize); + circBuf.Reset(); + break; + } + if (head->size > dataSize) { + break; + } + NetPacket pkt(head->idMsg); + if ((head->size > 0) && (!pkt.Write(&buf[headSize], head->size))) { + SEN_HILOGW("Error writing data in the NetPacket. It will be retried next time. messageid:%{public}d," + "size:%{public}d", head->idMsg, head->size); + break; + } + if (!circBuf.SeekReadPos(pkt.GetPacketLength())) { + SEN_HILOGW("Set read position error, and this error cannot be recovered, and the buffer will be reset." + " packetSize:%{public}d unreadSize:%{public}d", pkt.GetPacketLength(), unreadSize); + circBuf.Reset(); + break; + } + callbackFun(pkt); + if (circBuf.IsEmpty()) { + circBuf.Reset(); + break; + } + } +} + +void StreamSocket::EpollClose() +{ + if (epollFd_ >= 0) { + close(epollFd_); + epollFd_ = -1; + } +} + +void StreamSocket::Close() +{ + if (fd_ >= 0) { + auto rf = close(fd_); + if (rf > 0) { + SEN_HILOGE("Socket close failed rf:%{public}d", rf); + } + } + fd_ = -1; +} + +int32_t StreamSocket::GetFd() const +{ + return fd_; +} +int32_t StreamSocket::GetEpollFd() const +{ + return epollFd_; +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file -- Gitee From 38654354307e5c1c71a90dab55a6bc158a0b19cf Mon Sep 17 00:00:00 2001 From: hui1975 Date: Sat, 4 Mar 2023 06:20:02 +0000 Subject: [PATCH 02/53] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: Icee07f66eb2b874cde0cd86aa7e66c129fb5bd41 --- .../native/sensor/include/i_sensor_service.h | 6 +- .../sensor/include/sensor_agent_proxy.h | 2 +- .../sensor/include/sensor_service_client.h | 4 +- .../sensor/include/sensor_service_proxy.h | 2 +- .../native/sensor/src/sensor_agent_proxy.cpp | 62 ++++++++-------- .../sensor/src/sensor_service_client.cpp | 14 ++-- .../sensor/src/sensor_service_proxy.cpp | 70 +++++++++---------- interfaces/native/include/sensor_agent.h | 4 +- interfaces/native/include/sensor_agent_type.h | 6 +- interfaces/native/src/sensor_agent.cpp | 8 +-- .../test/unittest/sensor_power_test.cpp | 58 +++++++-------- interfaces/plugin/BUILD.gn | 2 +- services/sensor/include/sensor_service.h | 2 +- services/sensor/include/sensor_service_stub.h | 2 +- .../sensor/include/sensor_suspend_policy.h | 7 +- services/sensor/src/sensor_service.cpp | 17 +++-- services/sensor/src/sensor_service_stub.cpp | 18 ++--- services/sensor/src/sensor_suspend_policy.cpp | 33 +++++---- test/unittest/common/include/system_info.h | 1 + utils/common/BUILD.gn | 9 +-- utils/common/include/sensors_errors.h | 6 +- .../{app_sensor.h => subscribe_info.h} | 39 ++++------- .../{app_sensor.cpp => subscribe_info.cpp} | 54 +++++++------- utils/ipc/BUILD.gn | 9 +-- utils/ipc/src/circle_stream_buffer.cpp | 2 +- utils/ipc/src/net_packet.cpp | 11 +-- 26 files changed, 221 insertions(+), 227 deletions(-) rename utils/common/include/{app_sensor.h => subscribe_info.h} (58%) rename utils/common/src/{app_sensor.cpp => subscribe_info.cpp} (60%) diff --git a/frameworks/native/sensor/include/i_sensor_service.h b/frameworks/native/sensor/include/i_sensor_service.h index 23ca0c08..d6da491e 100755 --- a/frameworks/native/sensor/include/i_sensor_service.h +++ b/frameworks/native/sensor/include/i_sensor_service.h @@ -21,10 +21,10 @@ #include "errors.h" #include "iremote_broker.h" -#include "app_sensor.h" #include "i_sensor_client.h" #include "sensor_basic_data_channel.h" #include "sensor.h" +#include "subscribe_info.h" namespace OHOS { namespace Sensors { @@ -42,7 +42,7 @@ public: virtual ErrCode DestroySensorChannel(sptr sensorClient) = 0; virtual ErrCode SuspendSensors(int32_t pid) = 0; virtual ErrCode ResumeSensors(int32_t pid) = 0; - virtual ErrCode GetAppSensorList(int32_t pid, std::vector &appSensorList) = 0; + virtual ErrCode GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) = 0; virtual ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) = 0; virtual ErrCode DestroySocketChannel(const sptr &sensorClient) = 0; virtual ErrCode EnableClientInfoCallback() = 0; @@ -57,7 +57,7 @@ public: DESTROY_SENSOR_CHANNEL, SUSPEND_SENSORS, RESUME_SENSORS, - GET_APP_SENSOR_LIST, + GET_SUBSCRIBE_INFO_LIST, CREATE_SOCKET_CHANNEL, DESTROY_SOCKET_CHANNEL, ENABLE_CLIENT_INFO_CALLBACK, diff --git a/frameworks/native/sensor/include/sensor_agent_proxy.h b/frameworks/native/sensor/include/sensor_agent_proxy.h index d4259ef4..ddb0684e 100644 --- a/frameworks/native/sensor/include/sensor_agent_proxy.h +++ b/frameworks/native/sensor/include/sensor_agent_proxy.h @@ -45,7 +45,7 @@ public: int32_t GetAllSensors(SensorInfo **sensorInfo, int32_t *count) const; int32_t SuspendSensors(int32_t pid) const; int32_t ResumeSensors(int32_t pid) const; - int32_t GetAppSensors(int32_t pid, AppSensorInfo **appSensorInfos, int32_t *count) const; + int32_t GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **subscribeSensorInfos, int32_t *count) const; int32_t RegisterClientInfoCallback(ClientInfoCallback callback) const; int32_t UnregisterClientInfoCallback(ClientInfoCallback callback) const; diff --git a/frameworks/native/sensor/include/sensor_service_client.h b/frameworks/native/sensor/include/sensor_service_client.h index 722fb5c3..ea17de0b 100755 --- a/frameworks/native/sensor/include/sensor_service_client.h +++ b/frameworks/native/sensor/include/sensor_service_client.h @@ -23,7 +23,6 @@ #include "iservice_registry.h" #include "singleton.h" -#include "app_sensor.h" #include "sensor_agent_type.h" #include "sensor_basic_data_channel.h" #include "sensor_basic_info.h" @@ -32,6 +31,7 @@ #include "sensor.h" #include "sensor_service_proxy.h" #include "stream_socket.h" +#include "subscribe_info.h" namespace OHOS { namespace Sensors { @@ -47,7 +47,7 @@ public: bool IsValid(int32_t sensorId); int32_t SuspendSensors(int32_t pid); int32_t ResumeSensors(int32_t pid); - int32_t GetAppSensorList(int32_t pid, std::vector &appSensorList); + int32_t GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList); int32_t RegisterClientInfoCallback(ClientInfoCallback callback, sptr sensorDataChannel); int32_t UnregisterClientInfoCallback(ClientInfoCallback callback); diff --git a/frameworks/native/sensor/include/sensor_service_proxy.h b/frameworks/native/sensor/include/sensor_service_proxy.h index efabec2a..49523092 100755 --- a/frameworks/native/sensor/include/sensor_service_proxy.h +++ b/frameworks/native/sensor/include/sensor_service_proxy.h @@ -37,7 +37,7 @@ public: ErrCode DestroySensorChannel(sptr sensorClient) override; ErrCode SuspendSensors(int32_t pid) override; ErrCode ResumeSensors(int32_t pid) override; - ErrCode GetAppSensorList(int32_t pid, std::vector &appSensorList) override; + ErrCode GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) override; ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) override; ErrCode DestroySocketChannel(const sptr &sensorClient) override; ErrCode EnableClientInfoCallback() override; diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index 0959dae4..919d9c2d 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -39,8 +39,8 @@ std::recursive_mutex SensorAgentProxy::subscribeMutex_; std::mutex SensorAgentProxy::chanelMutex_; std::mutex sensorInfoMutex_; SensorInfo *sensorInfos_ = nullptr; -std::mutex appSensorInfoMutex_; -AppSensorInfo *appSensorInfo_ = nullptr; +std::mutex subscribeSensorInfoMutex_; +SubscribeSensorInfo *subscribeSensorInfos_ = nullptr; int32_t sensorInfoCount_ = 0; std::map SensorAgentProxy::g_subscribeMap; std::map SensorAgentProxy::g_unsubscribeMap; @@ -269,9 +269,9 @@ int32_t SensorAgentProxy::SetMode(int32_t sensorId, const SensorUser *user, int3 void SensorAgentProxy::ClearSensorInfos() const { - if (appSensorInfo_ != nullptr) { - free(appSensorInfo_); - appSensorInfo_ = nullptr; + if (subscribeSensorInfos_ != nullptr) { + free(subscribeSensorInfos_); + subscribeSensorInfos_ = nullptr; } CHKPV(sensorInfos_); free(sensorInfos_); @@ -366,47 +366,47 @@ int32_t SensorAgentProxy::ResumeSensors(int32_t pid) const return ret; } -int32_t SensorAgentProxy::GetAppSensors(int32_t pid, AppSensorInfo **appSensorInfos, int32_t *count) const +int32_t SensorAgentProxy::GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **subscribeSensorInfos, int32_t *count) const { CALL_LOG_ENTER; if (pid < 0) { SEN_HILOGE("Pid is invalid, %{public}d", pid); return PARAMETER_ERROR; } - CHKPR(appSensorInfos, OHOS::Sensors::ERROR); + CHKPR(subscribeSensorInfos, OHOS::Sensors::ERROR); CHKPR(count, OHOS::Sensors::ERROR); - std::lock_guard appSensorInfoLock(appSensorInfoMutex_); - if (appSensorInfo_ != nullptr) { - free(appSensorInfo_); - appSensorInfo_ = nullptr; + std::lock_guard subscribeSensorInfoLock(subscribeSensorInfoMutex_); + if (subscribeSensorInfos_ != nullptr) { + free(subscribeSensorInfos_); + subscribeSensorInfos_ = nullptr; } - std::vector appSensorList; - int32_t ret = SenClient.GetAppSensorList(pid, appSensorList); + std::vector subscribeInfoList; + int32_t ret = SenClient.GetSubscribeInfoList(pid, subscribeInfoList); if (ret != 0) { - SEN_HILOGE("Get app sensor list failed, ret:%{public}d", ret); + SEN_HILOGE("Get subscribe info list failed, ret:%{public}d", ret); return ERROR; } - if (appSensorList.empty()) { - SEN_HILOGE("App sensor list is empty, pid:%{public}d", pid); + if (subscribeInfoList.empty()) { + SEN_HILOGE("Subscribe info list is empty, pid:%{public}d", pid); return ERROR; } - size_t appSensorInfoCount = appSensorList.size(); - if (appSensorInfoCount > MAX_SENSOR_LIST_SIZE) { - SEN_HILOGE("The number of app sensors exceeds the maximum value, count:%{public}d", appSensorInfoCount); + size_t subscribeInfoCount = subscribeInfoList.size(); + if (subscribeInfoCount > MAX_SENSOR_LIST_SIZE) { + SEN_HILOGE("The number of subscribe info exceeds the maximum value, count:%{public}d", subscribeInfoCount); return ERROR; } - appSensorInfo_ = (AppSensorInfo *)malloc(sizeof(AppSensorInfo) * appSensorInfoCount); - CHKPR(appSensorInfo_, ERROR); - for (size_t i = 0; i < appSensorInfoCount; ++i) { - AppSensorInfo *curAppSensor = appSensorInfo_ + i; - curAppSensor->pid = appSensorList[i].GetPid(); - curAppSensor->sensorId = appSensorList[i].GetSensorId(); - curAppSensor->isActive = appSensorList[i].IsActive(); - curAppSensor->samplingPeriodNs = appSensorList[i].GetSamplingPeriodNs(); - curAppSensor->maxReportDelayNs = appSensorList[i].GetMaxReportDelayNs(); - } - *appSensorInfos = appSensorInfo_; - *count = static_cast(appSensorInfoCount); + subscribeSensorInfos_ = (SubscribeSensorInfo *)malloc(sizeof(SubscribeSensorInfo) * subscribeInfoCount); + CHKPR(subscribeSensorInfos_, ERROR); + for (size_t i = 0; i < subscribeInfoCount; ++i) { + SubscribeSensorInfo *curSubscribeInfo= subscribeSensorInfos_ + i; + curSubscribeInfo->pid = subscribeInfoList[i].GetPid(); + curSubscribeInfo->sensorId = subscribeInfoList[i].GetSensorId(); + curSubscribeInfo->isActive = subscribeInfoList[i].IsActive(); + curSubscribeInfo->samplingPeriodNs = subscribeInfoList[i].GetSamplingPeriodNs(); + curSubscribeInfo->maxReportDelayNs = subscribeInfoList[i].GetMaxReportDelayNs(); + } + *subscribeSensorInfos = subscribeSensorInfos_; + *count = static_cast(subscribeInfoCount); return SUCCESS; } diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index 7f237cc8..9728f340 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -264,7 +264,7 @@ int32_t SensorServiceClient::ResumeSensors(int32_t pid) FinishTrace(HITRACE_TAG_SENSORS); return ret; } -int32_t SensorServiceClient::GetAppSensorList(int32_t pid, std::vector &appSensorList) +int32_t SensorServiceClient::GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) { CALL_LOG_ENTER; int32_t ret = InitServiceClient(); @@ -273,8 +273,8 @@ int32_t SensorServiceClient::GetAppSensorList(int32_t pid, std::vectorGetAppSensorList(pid, appSensorList); + StartTrace(HITRACE_TAG_SENSORS, "GetSubscribeInfoList"); + ret = sensorServer_->GetSubscribeInfoList(pid, subscribeInfoList); FinishTrace(HITRACE_TAG_SENSORS); return ret; } @@ -379,9 +379,9 @@ void SensorServiceClient::HandleNetPacke(NetPacket &pkt) if (id != MessageId::CLIENT_INFO) { return; } - AppSensorInfo appSensorInfo; - pkt >> appSensorInfo.pid >> appSensorInfo.sensorId >> appSensorInfo.isActive >> - appSensorInfo.samplingPeriodNs >> appSensorInfo.maxReportDelayNs; + SubscribeSensorInfo subscribeSensorInfo; + pkt >> subscribeSensorInfo.pid >> subscribeSensorInfo.sensorId >> subscribeSensorInfo.isActive >> + subscribeSensorInfo.samplingPeriodNs >> subscribeSensorInfo.maxReportDelayNs; if (pkt.ChkRWError()) { SEN_HILOGE("Packet read type failed"); return; @@ -389,7 +389,7 @@ void SensorServiceClient::HandleNetPacke(NetPacket &pkt) std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); for (auto callback : clientInfoCallbackSet_) { if (callback != nullptr) { - callback(&appSensorInfo); + callback(&subscribeSensorInfo); } } } diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 975ce441..4ef9ddcc 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -46,19 +46,19 @@ ErrCode SensorServiceProxy::EnableSensor(int32_t sensorId, int64_t samplingPerio MessageOption option; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { SEN_HILOGE("write descriptor failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } if (!data.WriteInt32(sensorId)) { SEN_HILOGE("write sensorId failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } if (!data.WriteInt64(samplingPeriodNs)) { SEN_HILOGE("write samplingPeriodNs failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } if (!data.WriteInt64(maxReportDelayNs)) { SEN_HILOGE("write maxReportDelayNs failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } sptr remote = Remote(); CHKPR(remote, ERROR); @@ -78,11 +78,11 @@ ErrCode SensorServiceProxy::DisableSensor(int32_t sensorId) MessageOption option; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { SEN_HILOGE("write descriptor failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } if (!data.WriteInt32(sensorId)) { SEN_HILOGE("write sensorId failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } sptr remote = Remote(); CHKPR(remote, ERROR); @@ -147,12 +147,12 @@ ErrCode SensorServiceProxy::TransferDataChannel(const sptrSendToBinder(data); if (!data.WriteRemoteObject(sensorClient)) { SEN_HILOGE("sensorClient failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } sptr remote = Remote(); CHKPR(remote, ERROR); @@ -174,11 +174,11 @@ ErrCode SensorServiceProxy::DestroySensorChannel(sptr sensorClien MessageOption option; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { SEN_HILOGE("write descriptor failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } if (!data.WriteRemoteObject(sensorClient)) { SEN_HILOGE("write sensorClient failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } sptr remote = Remote(); CHKPR(remote, ERROR); @@ -196,11 +196,11 @@ ErrCode SensorServiceProxy::SuspendSensors(int32_t pid) MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { SEN_HILOGE("Write descriptor failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } if (!data.WriteInt32(pid)) { SEN_HILOGE("Write pid failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } sptr remote = Remote(); CHKPR(remote, ERROR); @@ -220,11 +220,11 @@ ErrCode SensorServiceProxy::ResumeSensors(int32_t pid) MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { SEN_HILOGE("Write descriptor failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } if (!data.WriteInt32(pid)) { SEN_HILOGE("Write pid failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } sptr remote = Remote(); CHKPR(remote, ERROR); @@ -239,41 +239,41 @@ ErrCode SensorServiceProxy::ResumeSensors(int32_t pid) return static_cast(ret); } -ErrCode SensorServiceProxy::GetAppSensorList(int32_t pid, std::vector &appSensorList) +ErrCode SensorServiceProxy::GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) { MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { SEN_HILOGE("Write descriptor failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } if (!data.WriteInt32(pid)) { SEN_HILOGE("Write pid failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } sptr remote = Remote(); CHKPR(remote, ERROR); MessageParcel reply; MessageOption option; - int32_t ret = remote->SendRequest(ISensorService::GET_APP_SENSOR_LIST, data, reply, option); + int32_t ret = remote->SendRequest(ISensorService::GET_SUBSCRIBE_INFO_LIST, data, reply, option); if (ret != NO_ERROR) { HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SENSOR_SERVICE_IPC_EXCEPTION", - HiSysEvent::EventType::FAULT, "PKG_NAME", "GetAppSensorList", "ERROR_CODE", ret); + HiSysEvent::EventType::FAULT, "PKG_NAME", "GetSubscribeInfoList", "ERROR_CODE", ret); SEN_HILOGE("Failed, ret:%{public}d", ret); return static_cast(ret); } - int32_t appSensorCount; - if (!reply.ReadInt32(appSensorCount)) { - SEN_HILOGE("Parcel read appSensorCount failed"); - return READ_MSG_ERR; + int32_t subscribeInfoCount; + if (!reply.ReadInt32(subscribeInfoCount)) { + SEN_HILOGE("Parcel read subscribeInfoCount failed"); + return READ_PARCEL_ERR; } - AppSensor appSensor; - for (int32_t i = 0; i < appSensorCount; ++i) { - auto tmpAppSensor = appSensor.Unmarshalling(reply); - if (tmpAppSensor == nullptr) { - SEN_HILOGE("Current appSensor is nullptr, i:%{public}d", i); + SubscribeInfo subscribeInfo; + for (int32_t i = 0; i < subscribeInfoCount; ++i) { + auto tmpSubscribeInfo = subscribeInfo.Unmarshalling(reply); + if (tmpSubscribeInfo == nullptr) { + SEN_HILOGE("Current subscribeInfo is nullptr, i:%{public}d", i); continue; } - appSensorList.push_back(*tmpAppSensor); + subscribeInfoList.push_back(*tmpSubscribeInfo); } return static_cast(ret); } @@ -284,11 +284,11 @@ ErrCode SensorServiceProxy::CreateSocketChannel(int32_t &clientFd, const sptr &sens MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { SEN_HILOGE("write descriptor failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } if (!data.WriteRemoteObject(sensorClient)) { SEN_HILOGE("Write sensorClient failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } sptr remote = Remote(); CHKPR(remote, ERROR); @@ -339,7 +339,7 @@ ErrCode SensorServiceProxy::EnableClientInfoCallback() MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { SEN_HILOGE("write descriptor failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } sptr remote = Remote(); CHKPR(remote, ERROR); @@ -359,7 +359,7 @@ ErrCode SensorServiceProxy::DisableClientInfoCallback() MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { SEN_HILOGE("write descriptor failed"); - return WRITE_MSG_ERR; + return WRITE_PARCEL_ERR; } sptr remote = Remote(); CHKPR(remote, ERROR); diff --git a/interfaces/native/include/sensor_agent.h b/interfaces/native/include/sensor_agent.h index ff86b534..afc4331f 100755 --- a/interfaces/native/include/sensor_agent.h +++ b/interfaces/native/include/sensor_agent.h @@ -149,13 +149,13 @@ int32_t ResumeSensors(int32_t pid); * @brief 查询一个进程订阅的所有传感器的信息 * * @param pid 进程号 - * @param appSensorInfos 返回进程订阅的所有传感器信息 + * @param subscribeSensorInfos 返回进程订阅的所有传感器信息 * @param count 返回进程订阅的传感器数量 * @return 返回0表示成功,否则表示失败 * * @since 10 */ -int32_t GetAppSensors(int32_t pid, AppSensorInfo **appSensorInfos, int32_t *count); +int32_t GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **subscribeSensorInfos, int32_t *count); /** * @brief 注册传感器订阅信息上报函数 * diff --git a/interfaces/native/include/sensor_agent_type.h b/interfaces/native/include/sensor_agent_type.h index eb1dc419..b298ad0d 100644 --- a/interfaces/native/include/sensor_agent_type.h +++ b/interfaces/native/include/sensor_agent_type.h @@ -395,15 +395,15 @@ typedef struct WearDetectionData { float value; } WearDetectionData; -typedef struct AppSensorInfo { +typedef struct SubscribeSensorInfo { int32_t pid = -1; /**< PID */ int32_t sensorId = -1; /**< Sensor ID */ bool isActive = false; /**< Whether the process enable the sensor */ int64_t samplingPeriodNs = -1; /**< Sample period, in ns */ int64_t maxReportDelayNs = -1; /**< Maximum Report Delay, in ns */ -} AppSensorInfo; +} SubscribeSensorInfo; -typedef void (*ClientInfoCallback)(AppSensorInfo *appSensorInfo); +typedef void (*ClientInfoCallback)(SubscribeSensorInfo *subscribeSensorInfo); #ifdef __cplusplus #if __cplusplus diff --git a/interfaces/native/src/sensor_agent.cpp b/interfaces/native/src/sensor_agent.cpp index 604def3c..559abc89 100755 --- a/interfaces/native/src/sensor_agent.cpp +++ b/interfaces/native/src/sensor_agent.cpp @@ -178,18 +178,18 @@ int32_t ResumeSensors(int32_t pid) return ret; } -int32_t GetAppSensors(int32_t pid, AppSensorInfo **appSensorInfos, int32_t *count) +int32_t GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **subscribeSensorInfos, int32_t *count) { - CHKPR(appSensorInfos, OHOS::Sensors::ERROR); + CHKPR(subscribeSensorInfos, OHOS::Sensors::ERROR); CHKPR(count, OHOS::Sensors::ERROR); const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("Proxy is nullptr"); return SERVICE_EXCEPTION; } - int32_t ret = proxy->GetAppSensors(pid, appSensorInfos, count); + int32_t ret = proxy->GetSubscribeInfos(pid, subscribeSensorInfos, count); if (ret != OHOS::ERR_OK) { - SEN_HILOGE("GetAppSensors failed, ret:%{public}d", ret); + SEN_HILOGE("GetSubscribeInfos failed, ret:%{public}d", ret); return NormalizeErrCode(ret); } return ret; diff --git a/interfaces/native/test/unittest/sensor_power_test.cpp b/interfaces/native/test/unittest/sensor_power_test.cpp index 9e3f741a..bfb4bc1f 100644 --- a/interfaces/native/test/unittest/sensor_power_test.cpp +++ b/interfaces/native/test/unittest/sensor_power_test.cpp @@ -90,28 +90,28 @@ void SensorDataCallbackImpl(SensorEvent *event) event[0].sensorTypeId, event[0].version, event[0].dataLen, *(sensorData)); } -void ClientInfoCallbackImpl(AppSensorInfo *appSensorInfo) +void ClientInfoCallbackImpl(SubscribeSensorInfo *subscribeSensorInfo) { - if (appSensorInfo == nullptr) { - SEN_HILOGE("appSensorInfo is null"); + if (subscribeSensorInfo == nullptr) { + SEN_HILOGE("subscribeSensorInfo is null"); return; } SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", - appSensorInfo->pid, appSensorInfo->sensorId, appSensorInfo->isActive, - appSensorInfo->samplingPeriodNs, appSensorInfo->maxReportDelayNs); + subscribeSensorInfo->pid, subscribeSensorInfo->sensorId, subscribeSensorInfo->isActive, + subscribeSensorInfo->samplingPeriodNs, subscribeSensorInfo->maxReportDelayNs); } -void ClientInfoCallbackImpl2(AppSensorInfo *appSensorInfo) +void ClientInfoCallbackImpl2(SubscribeSensorInfo *subscribeSensorInfo) { - if (appSensorInfo == nullptr) { - SEN_HILOGE("appSensorInfo is null"); + if (subscribeSensorInfo == nullptr) { + SEN_HILOGE("subscribeSensorInfo is null"); return; } SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", - appSensorInfo->pid, appSensorInfo->sensorId, appSensorInfo->isActive, - appSensorInfo->samplingPeriodNs, appSensorInfo->maxReportDelayNs); + subscribeSensorInfo->pid, subscribeSensorInfo->sensorId, subscribeSensorInfo->isActive, + subscribeSensorInfo->samplingPeriodNs, subscribeSensorInfo->maxReportDelayNs); } HWTEST_F(SensorPowerTest, SuspendSensorsTest_001, TestSize.Level1) @@ -130,13 +130,13 @@ HWTEST_F(SensorPowerTest, ResumeSensorsTest_001, TestSize.Level1) ASSERT_NE(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, GetAppSensorsTest_001, TestSize.Level1) +HWTEST_F(SensorPowerTest, GetSubscribeInfosTest_001, TestSize.Level1) { // 查询接口异常用例 - SEN_HILOGI("GetAppSensorsTest_001 in"); - AppSensorInfo *appSensorInfos {nullptr}; + SEN_HILOGI("GetSubscribeInfosTest_001 in"); + SubscribeSensorInfo *subscribeSensorInfo {nullptr}; int32_t count { 0 }; - int32_t ret = GetAppSensors(invalidValue, &appSensorInfos, &count); + int32_t ret = GetSubscribeInfos(invalidValue, &subscribeSensorInfo, &count); ASSERT_NE(ret, OHOS::Sensors::SUCCESS); } @@ -173,15 +173,15 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_001, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); std::this_thread::sleep_for(std::chrono::milliseconds(500)); - AppSensorInfo *appSensorInfos {nullptr}; + SubscribeSensorInfo *subscribeSensorInfo {nullptr}; int32_t count { 0 }; - ret = GetAppSensors(process_pid, &appSensorInfos, &count); + ret = GetSubscribeInfos(process_pid, &subscribeSensorInfo, &count); for (int32_t i = 0; i < count; ++i) { - AppSensorInfo *curAppSensor = appSensorInfos + i; + SubscribeSensorInfo *curSubscribeSensorInfo = subscribeSensorInfo + i; SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", - i, curAppSensor->pid, curAppSensor->sensorId, curAppSensor->isActive, - curAppSensor->samplingPeriodNs, curAppSensor->maxReportDelayNs); + i, curSubscribeSensorInfo->pid, curSubscribeSensorInfo->sensorId, curSubscribeSensorInfo->isActive, + curSubscribeSensorInfo->samplingPeriodNs, curSubscribeSensorInfo->maxReportDelayNs); } ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); @@ -218,15 +218,15 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_002, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); std::this_thread::sleep_for(std::chrono::milliseconds(3000)); - AppSensorInfo *appSensorInfos {nullptr}; + SubscribeSensorInfo *subscribeSensorInfo {nullptr}; int32_t count { 0 }; - ret = GetAppSensors(process_pid, &appSensorInfos, &count); + ret = GetSubscribeInfos(process_pid, &subscribeSensorInfo, &count); for (int32_t i = 0; i < count; ++i) { - AppSensorInfo *curAppSensor = appSensorInfos + i; + SubscribeSensorInfo *curSubscribeSensorInfo = subscribeSensorInfo + i; SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", - i, curAppSensor->pid, curAppSensor->sensorId, curAppSensor->isActive, - curAppSensor->samplingPeriodNs, curAppSensor->maxReportDelayNs); + i, curSubscribeSensorInfo->pid, curSubscribeSensorInfo->sensorId, curSubscribeSensorInfo->isActive, + curSubscribeSensorInfo->samplingPeriodNs, curSubscribeSensorInfo->maxReportDelayNs); } ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); @@ -263,15 +263,15 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_003, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); - AppSensorInfo *appSensorInfos {nullptr}; + SubscribeSensorInfo *subscribeSensorInfo {nullptr}; int32_t count { 0 }; - ret = GetAppSensors(process_pid, &appSensorInfos, &count); + ret = GetSubscribeInfos(process_pid, &subscribeSensorInfo, &count); for (int32_t i = 0; i < count; ++i) { - AppSensorInfo *curAppSensor = appSensorInfos + i; + SubscribeSensorInfo *curSubscribeSensorInfo = subscribeSensorInfo + i; SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", - i, curAppSensor->pid, curAppSensor->sensorId, curAppSensor->isActive, - curAppSensor->samplingPeriodNs, curAppSensor->maxReportDelayNs); + i, curSubscribeSensorInfo->pid, curSubscribeSensorInfo->sensorId, curSubscribeSensorInfo->isActive, + curSubscribeSensorInfo->samplingPeriodNs, curSubscribeSensorInfo->maxReportDelayNs); } ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); diff --git a/interfaces/plugin/BUILD.gn b/interfaces/plugin/BUILD.gn index cd864d86..4c3db194 100644 --- a/interfaces/plugin/BUILD.gn +++ b/interfaces/plugin/BUILD.gn @@ -21,7 +21,7 @@ ohos_shared_library("libsensor") { "//third_party/libuv/include", "//commonlibrary/c_utils/base/include", "./include", - "//base/sensors/sensor/utils/common/include", + "./../../utils/common/include", "//foundation/arkui/napi/interfaces/inner_api/napi", ] defines = [ diff --git a/services/sensor/include/sensor_service.h b/services/sensor/include/sensor_service.h index da3cf223..68ce80bd 100644 --- a/services/sensor/include/sensor_service.h +++ b/services/sensor/include/sensor_service.h @@ -58,7 +58,7 @@ public: void ProcessDeathObserver(const wptr &object); ErrCode SuspendSensors(int32_t pid) override; ErrCode ResumeSensors(int32_t pid) override; - ErrCode GetAppSensorList(int32_t pid, std::vector &appSensorList) override; + ErrCode GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) override; ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) override; ErrCode DestroySocketChannel(const sptr &sensorClient) override; ErrCode EnableClientInfoCallback() override; diff --git a/services/sensor/include/sensor_service_stub.h b/services/sensor/include/sensor_service_stub.h index d2830b2a..6e79f402 100644 --- a/services/sensor/include/sensor_service_stub.h +++ b/services/sensor/include/sensor_service_stub.h @@ -41,7 +41,7 @@ private: ErrCode DestroyDataChannelInner(MessageParcel &data, MessageParcel &reply); ErrCode SuspendSensorsInner(MessageParcel &data, MessageParcel &reply); ErrCode ResumeSensorsInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetAppSensorListInner(MessageParcel &data, MessageParcel &reply); + ErrCode GetSubscribeInfoListInner(MessageParcel &data, MessageParcel &reply); ErrCode CreateSocketChannelInner(MessageParcel &data, MessageParcel &reply); ErrCode DestroySocketChannelInner(MessageParcel &data, MessageParcel &reply); ErrCode EnableClientInfoCallbackInner(MessageParcel &data, MessageParcel &reply); diff --git a/services/sensor/include/sensor_suspend_policy.h b/services/sensor/include/sensor_suspend_policy.h index ea9cca34..5cf18d38 100644 --- a/services/sensor/include/sensor_suspend_policy.h +++ b/services/sensor/include/sensor_suspend_policy.h @@ -22,7 +22,7 @@ #include "nocopyable.h" -#include "app_sensor.h" +#include "subscribe_info.h" #include "client_info.h" #include "sensor_agent_type.h" #include "sensor_hdi_connection.h" @@ -36,9 +36,8 @@ class SensorSuspendPolicy : public Singleton{ public: ErrCode DoSuspend(int32_t pid); ErrCode DoResume(int32_t pid); - ErrCode GetAppSensorList(int32_t pid, std::vector &appSensorList); - void ReportClientInfo(int32_t pid, const SensorStatus sensorStatus, - const std::vector &sessionList); + ErrCode GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList); + void ReportClientInfo(SubscribeSensorInfo subscribeSensorInfo, const std::vector &sessionList); private: bool CheckFreezingSensor(int32_t sensorId); diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 5e03ce19..9f34a15b 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -27,6 +27,7 @@ #include "securec.h" #include "sensor.h" #include "sensor_dump.h" +#include "sensor_agent_type.h" #include "sensors_errors.h" #include "system_ability_definition.h" @@ -459,16 +460,16 @@ ErrCode SensorService::ResumeSensors(int32_t pid) return ERR_OK; } -ErrCode SensorService::GetAppSensorList(int32_t pid, std::vector &appSensorList) +ErrCode SensorService::GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) { CALL_LOG_ENTER; if (pid < 0) { SEN_HILOGE("Pid is invalid, pid:%{public}d", pid); return CLIENT_PID_INVALID_ERR; } - int32_t ret = suspendPolicy_.GetAppSensorList(pid, appSensorList); + int32_t ret = suspendPolicy_.GetSubscribeInfoList(pid, subscribeInfoList); if (ret != ERR_OK) { - SEN_HILOGE("Get pid sensor list failed, pid:%{public}d", pid); + SEN_HILOGE("Get subscribe info list failed, pid:%{public}d", pid); return ERROR; } return ERR_OK; @@ -528,9 +529,13 @@ void SensorService::ReportClientInfo(int32_t sensorId, bool isActive, int32_t pi } } SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); - SensorStatus sensorStatus(sensorId, isActive, sensorInfo.GetSamplingPeriodNs(), - sensorInfo.GetMaxReportDelayNs()); - suspendPolicy_.ReportClientInfo(pid, sensorStatus, sessionList); + SubscribeSensorInfo subscribeSensorInfo; + subscribeSensorInfo.pid = pid; + subscribeSensorInfo.sensorId = sensorId; + subscribeSensorInfo.isActive = isActive; + subscribeSensorInfo.samplingPeriodNs = sensorInfo.GetSamplingPeriodNs(); + subscribeSensorInfo.maxReportDelayNs = sensorInfo.GetMaxReportDelayNs(); + suspendPolicy_.ReportClientInfo(subscribeSensorInfo, sessionList); } } // namespace Sensors } // namespace OHOS diff --git a/services/sensor/src/sensor_service_stub.cpp b/services/sensor/src/sensor_service_stub.cpp index 1c07334d..744ed910 100755 --- a/services/sensor/src/sensor_service_stub.cpp +++ b/services/sensor/src/sensor_service_stub.cpp @@ -44,7 +44,7 @@ SensorServiceStub::SensorServiceStub() baseFuncs_[DESTROY_SENSOR_CHANNEL] = &SensorServiceStub::DestroyDataChannelInner; baseFuncs_[SUSPEND_SENSORS] = &SensorServiceStub::SuspendSensorsInner; baseFuncs_[RESUME_SENSORS] = &SensorServiceStub::ResumeSensorsInner; - baseFuncs_[GET_APP_SENSOR_LIST] = &SensorServiceStub::GetAppSensorListInner; + baseFuncs_[GET_SUBSCRIBE_INFO_LIST] = &SensorServiceStub::GetSubscribeInfoListInner; baseFuncs_[CREATE_SOCKET_CHANNEL] = &SensorServiceStub::CreateSocketChannelInner; baseFuncs_[DESTROY_SOCKET_CHANNEL] = &SensorServiceStub::DestroySocketChannelInner; baseFuncs_[ENABLE_CLIENT_INFO_CALLBACK] = &SensorServiceStub::EnableClientInfoCallbackInner; @@ -192,7 +192,7 @@ ErrCode SensorServiceStub::ResumeSensorsInner(MessageParcel &data, MessageParcel return ResumeSensors(pid); } -ErrCode SensorServiceStub::GetAppSensorListInner(MessageParcel &data, MessageParcel &reply) +ErrCode SensorServiceStub::GetSubscribeInfoListInner(MessageParcel &data, MessageParcel &reply) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { @@ -204,13 +204,13 @@ ErrCode SensorServiceStub::GetAppSensorListInner(MessageParcel &data, MessagePar SEN_HILOGE("Parcel read failed"); return ERROR; } - std::vector appSensors; - GetAppSensorList(pid, appSensors); - int32_t appSensorCount = int32_t { appSensors.size() }; - reply.WriteInt32(appSensorCount); - for (int32_t i = 0; i < appSensorCount; i++) { - if (!appSensors[i].Marshalling(reply)) { - SEN_HILOGE("AppSensor %{public}d failed", i); + std::vector subscribeInfoList; + GetSubscribeInfoList(pid, subscribeInfoList); + int32_t subscribeInfoCount = int32_t { subscribeInfoList.size() }; + reply.WriteInt32(subscribeInfoCount); + for (int32_t i = 0; i < subscribeInfoCount; i++) { + if (!subscribeInfoList[i].Marshalling(reply)) { + SEN_HILOGE("SubscribeInfo %{public}d failed", i); return ERROR; } } diff --git a/services/sensor/src/sensor_suspend_policy.cpp b/services/sensor/src/sensor_suspend_policy.cpp index 8176953a..d098594d 100644 --- a/services/sensor/src/sensor_suspend_policy.cpp +++ b/services/sensor/src/sensor_suspend_policy.cpp @@ -16,6 +16,7 @@ #include "sensor_suspend_policy.h" #include "sensor.h" +#include "sensor_agent_type.h" namespace OHOS { namespace Sensors { @@ -192,38 +193,46 @@ ErrCode SensorSuspendPolicy::RestoreSensorInfo(int32_t sensorId, int32_t pid, in return ret; } -ErrCode SensorSuspendPolicy::GetAppSensorList(int32_t pid, std::vector &appSensorList) +ErrCode SensorSuspendPolicy::GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) { CALL_LOG_ENTER; std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); for (auto &sensorId : sensorIdList) { auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); - SensorStatus sensorStatus(sensorId, true, sensorInfo.GetSamplingPeriodNs(), - sensorInfo.GetMaxReportDelayNs()); - AppSensor appSensor(pid, sensorStatus); - appSensorList.push_back(appSensor); + SubscribeSensorInfo subscribeSensorInfo; + subscribeSensorInfo.pid = pid; + subscribeSensorInfo.sensorId = sensorId; + subscribeSensorInfo.isActive = true; + subscribeSensorInfo.samplingPeriodNs = sensorInfo.GetSamplingPeriodNs(); + subscribeSensorInfo.maxReportDelayNs = sensorInfo.GetMaxReportDelayNs(); + SubscribeInfo subscribeInfo(subscribeSensorInfo); + subscribeInfoList.push_back(subscribeInfo); } std::lock_guard pidSensorInfoLock(pidSensorInfoMutex_); auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); if (pidSensorInfoIt != pidSensorInfoMap_.end()) { std::unordered_map SensorInfoMap = pidSensorInfoIt->second; for (auto &sensorInfo : SensorInfoMap) { - SensorStatus sensorStatus(sensorInfo.first, false, sensorInfo.second.GetSamplingPeriodNs(), - sensorInfo.second.GetMaxReportDelayNs()); - AppSensor appSensor(pid, sensorStatus); - appSensorList.push_back(appSensor); + SubscribeSensorInfo subscribeSensorInfo; + subscribeSensorInfo.pid = pid; + subscribeSensorInfo.sensorId = sensorInfo.first; + subscribeSensorInfo.isActive = false; + subscribeSensorInfo.samplingPeriodNs = sensorInfo.second.GetSamplingPeriodNs(); + subscribeSensorInfo.maxReportDelayNs = sensorInfo.second.GetMaxReportDelayNs(); + SubscribeInfo subscribeInfo(subscribeSensorInfo); + subscribeInfoList.push_back(subscribeInfo); } } return ERR_OK; } -void SensorSuspendPolicy::ReportClientInfo(int32_t pid, const SensorStatus sensorStatus, +void SensorSuspendPolicy::ReportClientInfo(SubscribeSensorInfo subscribeSensorInfo, const std::vector &sessionList) { CALL_LOG_ENTER; NetPacket pkt(MessageId::CLIENT_INFO); - pkt << pid << sensorStatus.sensorId << sensorStatus.isActive << sensorStatus.samplingPeriodNs << - sensorStatus.maxReportDelayNs; + pkt << subscribeSensorInfo.pid << subscribeSensorInfo.sensorId << subscribeSensorInfo.isActive << + subscribeSensorInfo.samplingPeriodNs << subscribeSensorInfo.maxReportDelayNs; if (pkt.ChkRWError()) { SEN_HILOGE("Packet write data failed"); return; diff --git a/test/unittest/common/include/system_info.h b/test/unittest/common/include/system_info.h index 76ad756a..0a598969 100644 --- a/test/unittest/common/include/system_info.h +++ b/test/unittest/common/include/system_info.h @@ -37,6 +37,7 @@ public: double GetSystemCpuUsage(); double GetProcCpuUsage(const std::string& process_name); int32_t GetTaskPidFile(const std::string& process_name); + private: struct Total_Cpu_Occupy { char name[20] { 0 }; diff --git a/utils/common/BUILD.gn b/utils/common/BUILD.gn index c5b02656..5e1ef88f 100644 --- a/utils/common/BUILD.gn +++ b/utils/common/BUILD.gn @@ -13,25 +13,20 @@ import("//build/ohos.gni") -SUBSYSTEM_DIR = "//base/sensors" - ohos_shared_library("libsensor_utils") { sources = [ - "src/app_sensor.cpp", "src/permission_util.cpp", "src/report_data_callback.cpp", "src/sensor.cpp", "src/sensor_basic_data_channel.cpp", "src/sensor_basic_info.cpp", "src/sensor_channel_info.cpp", + "src/subscribe_info.cpp", ] include_dirs = [ "include", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", - "//drivers/peripheral/sensor/interfaces/include", - "$SUBSYSTEM_DIR/sensor/interfaces/native/include", + "./../../interfaces/native/include", ] external_deps = [ diff --git a/utils/common/include/sensors_errors.h b/utils/common/include/sensors_errors.h index 35335518..43edceab 100644 --- a/utils/common/include/sensors_errors.h +++ b/utils/common/include/sensors_errors.h @@ -87,9 +87,9 @@ enum { COPY_ERR = NO_EVENT + 1, REGIST_PERMISSION_CHANGED_ERR = COPY_ERR + 1, DUMP_PARAM_ERR = REGIST_PERMISSION_CHANGED_ERR + 1, - WRITE_MSG_ERR = DUMP_PARAM_ERR + 1, - READ_MSG_ERR = WRITE_MSG_ERR + 1, - SET_SENSOR_MODE_ERR = READ_MSG_ERR + 1, + WRITE_PARCEL_ERR = DUMP_PARAM_ERR + 1, + READ_PARCEL_ERR = WRITE_PARCEL_ERR + 1, + SET_SENSOR_MODE_ERR = READ_PARCEL_ERR + 1, SET_SENSOR_OPTION_ERR = SET_SENSOR_MODE_ERR + 1, REGIST_CALLBACK_ERR = SET_SENSOR_OPTION_ERR + 1, }; diff --git a/utils/common/include/app_sensor.h b/utils/common/include/subscribe_info.h similarity index 58% rename from utils/common/include/app_sensor.h rename to utils/common/include/subscribe_info.h index 18558e94..fbcd41b1 100644 --- a/utils/common/include/app_sensor.h +++ b/utils/common/include/subscribe_info.h @@ -13,29 +13,20 @@ * limitations under the License. */ -#ifndef APP_SENSOR_H -#define APP_SENSOR_H +#ifndef SUBSCRIBE_INFO_H +#define SUBSCRIBE_INFO_H #include "parcel.h" +#include "sensor_agent_type.h" + namespace OHOS { namespace Sensors { -struct SensorStatus { - int32_t sensorId {-1}; - bool isActive {false}; - int64_t samplingPeriodNs {-1}; - int64_t maxReportDelayNs {-1}; - SensorStatus() {} - SensorStatus(int32_t sensorId, bool isActive, int64_t samplingPeriodNs, int64_t maxReportDelayNs) - : sensorId(sensorId), isActive(isActive), samplingPeriodNs(samplingPeriodNs), - maxReportDelayNs(maxReportDelayNs) {} -}; - -class AppSensor : public Parcelable { +class SubscribeInfo : public Parcelable { public: - AppSensor() = default; - AppSensor(int32_t pid, SensorStatus sensorStatus); - virtual ~AppSensor() = default; + SubscribeInfo() = default; + SubscribeInfo(SubscribeSensorInfo subscribeSensorInfo); + virtual ~SubscribeInfo() = default; int32_t GetPid() const; void SetPid(int32_t pid); int32_t GetSensorId() const; @@ -47,15 +38,15 @@ public: int64_t GetMaxReportDelayNs() const; void SetMaxReportDelayNs(int64_t maxReportDelayNs); bool Marshalling(Parcel &parcel) const; - std::unique_ptr Unmarshalling(Parcel &parcel); + std::unique_ptr Unmarshalling(Parcel &parcel); private: - int32_t pid_ {-1}; - int32_t sensorId_ {-1}; - bool isActive_ {-1}; - int64_t samplingPeriodNs_ {-1}; - int64_t maxReportDelayNs_ {-1}; + int32_t pid_ { -1 }; + int32_t sensorId_ { -1 }; + bool isActive_ { -1 }; + int64_t samplingPeriodNs_ { -1 }; + int64_t maxReportDelayNs_ { -1 }; }; } // namespace Sensors } // namespace OHOS -#endif // APP_SENSOR_H \ No newline at end of file +#endif // SUBSCRIBE_INFO_H \ No newline at end of file diff --git a/utils/common/src/app_sensor.cpp b/utils/common/src/subscribe_info.cpp similarity index 60% rename from utils/common/src/app_sensor.cpp rename to utils/common/src/subscribe_info.cpp index 18668359..18c8605c 100644 --- a/utils/common/src/app_sensor.cpp +++ b/utils/common/src/subscribe_info.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "app_sensor.h" +#include "subscribe_info.h" #include "sensors_errors.h" @@ -21,69 +21,69 @@ namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; namespace { -constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "AppSensor" }; +constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SubscribeInfo" }; } -AppSensor::AppSensor(int32_t pid, SensorStatus sensorStatus) +SubscribeInfo::SubscribeInfo(SubscribeSensorInfo subscribeSensorInfo) { - pid_ = pid; - sensorId_ = sensorStatus.sensorId; - isActive_ = sensorStatus.isActive; - samplingPeriodNs_ = sensorStatus.samplingPeriodNs; - maxReportDelayNs_ = sensorStatus.maxReportDelayNs; + pid_ = subscribeSensorInfo.pid; + sensorId_ = subscribeSensorInfo.sensorId; + isActive_ = subscribeSensorInfo.isActive; + samplingPeriodNs_ = subscribeSensorInfo.samplingPeriodNs; + maxReportDelayNs_ = subscribeSensorInfo.maxReportDelayNs; } -int32_t AppSensor::GetPid() const +int32_t SubscribeInfo::GetPid() const { return pid_; } -void AppSensor::SetPid(int32_t pid) +void SubscribeInfo::SetPid(int32_t pid) { pid_ = pid; } -int32_t AppSensor::GetSensorId() const +int32_t SubscribeInfo::GetSensorId() const { return sensorId_; } -void AppSensor::SetSensorId(int32_t sensorId) +void SubscribeInfo::SetSensorId(int32_t sensorId) { sensorId_ = sensorId; } -bool AppSensor::IsActive() const +bool SubscribeInfo::IsActive() const { return isActive_; } -void AppSensor::Enable(bool isActive) +void SubscribeInfo::Enable(bool isActive) { isActive_ = isActive; } -int64_t AppSensor::GetSamplingPeriodNs() const +int64_t SubscribeInfo::GetSamplingPeriodNs() const { return samplingPeriodNs_; } -void AppSensor::SetSamplingPeriodNs(int64_t samplingPeriodNs) +void SubscribeInfo::SetSamplingPeriodNs(int64_t samplingPeriodNs) { samplingPeriodNs_ = samplingPeriodNs; } -int64_t AppSensor::GetMaxReportDelayNs() const +int64_t SubscribeInfo::GetMaxReportDelayNs() const { return maxReportDelayNs_; } -void AppSensor::SetMaxReportDelayNs(int64_t maxReportDelayNs) +void SubscribeInfo::SetMaxReportDelayNs(int64_t maxReportDelayNs) { maxReportDelayNs_ = maxReportDelayNs; } -bool AppSensor::Marshalling(Parcel &parcel) const +bool SubscribeInfo::Marshalling(Parcel &parcel) const { if (!parcel.WriteInt32(pid_)) { SEN_HILOGE("Write pid failed"); @@ -108,7 +108,7 @@ bool AppSensor::Marshalling(Parcel &parcel) const return true; } -std::unique_ptr AppSensor::Unmarshalling(Parcel &parcel) +std::unique_ptr SubscribeInfo::Unmarshalling(Parcel &parcel) { int32_t pid = -1; int32_t sensorId = -1; @@ -120,13 +120,13 @@ std::unique_ptr AppSensor::Unmarshalling(Parcel &parcel) SEN_HILOGE("ReadFromParcel is failed"); return nullptr; } - auto appSensor = std::make_unique(); - appSensor->SetPid(pid); - appSensor->SetSensorId(sensorId); - appSensor->Enable(isActive); - appSensor->SetSamplingPeriodNs(samplingPeriodNs); - appSensor->SetMaxReportDelayNs(maxReportDelayNs); - return appSensor; + auto subscribeInfo = std::make_unique(); + subscribeInfo->SetPid(pid); + subscribeInfo->SetSensorId(sensorId); + subscribeInfo->Enable(isActive); + subscribeInfo->SetSamplingPeriodNs(samplingPeriodNs); + subscribeInfo->SetMaxReportDelayNs(maxReportDelayNs); + return subscribeInfo; } } // namespace Sensors } // namespace OHOS \ No newline at end of file diff --git a/utils/ipc/BUILD.gn b/utils/ipc/BUILD.gn index 5986159a..3b78d1ff 100644 --- a/utils/ipc/BUILD.gn +++ b/utils/ipc/BUILD.gn @@ -13,8 +13,6 @@ import("//build/ohos.gni") -SUBSYSTEM_DIR = "//base/sensors" - ohos_shared_library("libsensor_ipc") { sources = [ "src/circle_stream_buffer.cpp", @@ -27,14 +25,9 @@ ohos_shared_library("libsensor_ipc") { include_dirs = [ "include", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", - "//drivers/peripheral/sensor/interfaces/include", - "$SUBSYSTEM_DIR/sensor/utils/common/include", + "./../common/include", ] - deps = [ "$SUBSYSTEM_DIR/sensor/utils/common:libsensor_utils" ] - external_deps = [ "access_token:libaccesstoken_sdk", "c_utils:utils", diff --git a/utils/ipc/src/circle_stream_buffer.cpp b/utils/ipc/src/circle_stream_buffer.cpp index a2c91f54..1f1845b2 100644 --- a/utils/ipc/src/circle_stream_buffer.cpp +++ b/utils/ipc/src/circle_stream_buffer.cpp @@ -44,7 +44,7 @@ bool CircleStreamBuffer::Write(const char *buf, size_t size) void CircleStreamBuffer::CopyDataToBegin() { int32_t unreadSize = UnreadSize(); - if (unreadSize > 0 && rPos_ > 0) { + if (unreadSize > 0 && rPos_ > 0 && sizeof(szBuff_) > wPos_) { int32_t pos = 0; for (int32_t i = rPos_; i <= wPos_;) { szBuff_[pos++] = szBuff_[i++]; diff --git a/utils/ipc/src/net_packet.cpp b/utils/ipc/src/net_packet.cpp index 7e3a3bae..00acc027 100644 --- a/utils/ipc/src/net_packet.cpp +++ b/utils/ipc/src/net_packet.cpp @@ -32,11 +32,12 @@ void NetPacket::MakeData(StreamBuffer &buf) const { PACKHEAD head = {msgId_, wPos_}; buf << head; - if (wPos_ > 0) { - if (!buf.Write(&szBuff_[0], wPos_)) { - SEN_HILOGE("Write data to stream failed, errCode:%{public}d", PROTO_STREAM_BUF_WRITE_FAIL); - return; - } + if (wPos_ < 0) { + return; + } + if (!buf.Write(&szBuff_[0], wPos_)) { + SEN_HILOGE("Write data to stream failed, errCode:%{public}d", PROTO_STREAM_BUF_WRITE_FAIL); + return; } } -- Gitee From 3ab0b48d692bc929e47c78fb02af5c039bbe5ecf Mon Sep 17 00:00:00 2001 From: hui1975 Date: Sat, 4 Mar 2023 07:37:44 +0000 Subject: [PATCH 03/53] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: If4f03b7e59cc2fe0148cd23bf1a898f9e1da890e --- .../client_info_file_descriptor_listener.cpp | 6 ++-- .../native/sensor/src/sensor_agent_proxy.cpp | 8 ++--- .../native/sensor/src/sensor_data_channel.cpp | 8 ++--- .../sensor/src/sensor_service_client.cpp | 3 +- .../sensor/src/sensor_service_proxy.cpp | 2 +- .../sensor/include/sensor_suspend_policy.h | 2 +- services/sensor/src/client_info.cpp | 8 ++--- services/sensor/src/sensor_service.cpp | 18 +++++----- services/sensor/src/sensor_suspend_policy.cpp | 21 +++++------ services/sensor/src/stream_server.cpp | 36 ++++--------------- 10 files changed, 41 insertions(+), 71 deletions(-) diff --git a/frameworks/native/sensor/src/client_info_file_descriptor_listener.cpp b/frameworks/native/sensor/src/client_info_file_descriptor_listener.cpp index 3e9a3d0c..4782e63a 100644 --- a/frameworks/native/sensor/src/client_info_file_descriptor_listener.cpp +++ b/frameworks/native/sensor/src/client_info_file_descriptor_listener.cpp @@ -35,7 +35,7 @@ void ClientInfoFileDescriptorListener::SetChannel(SensorDataChannel *channel) void ClientInfoFileDescriptorListener::OnReadable(int32_t fd) { if (fd < 0) { - SEN_HILOGE("Invalid fd:%{public}d", fd); + SEN_HILOGE("Invalid fd"); return; } char szBuf[PROTO_MAX_PACKET_BUF_SIZE] = {}; @@ -65,7 +65,7 @@ void ClientInfoFileDescriptorListener::OnReadable(int32_t fd) void ClientInfoFileDescriptorListener::OnShutdown(int32_t fd) { if (fd < 0) { - SEN_HILOGE("Invalid fd:%{public}d", fd); + SEN_HILOGE("Invalid fd"); } channel_->disconnect_(); } @@ -73,7 +73,7 @@ void ClientInfoFileDescriptorListener::OnShutdown(int32_t fd) void ClientInfoFileDescriptorListener::OnException(int32_t fd) { if (fd < 0) { - SEN_HILOGE("Invalid fd:%{public}d", fd); + SEN_HILOGE("Invalid fd"); } channel_->disconnect_(); } diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index 919d9c2d..7bb938a7 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -342,7 +342,7 @@ int32_t SensorAgentProxy::SuspendSensors(int32_t pid) const { CALL_LOG_ENTER; if (pid < 0) { - SEN_HILOGE("Pid is invalid, %{public}d", pid); + SEN_HILOGE("Pid is invalid"); return PARAMETER_ERROR; } int32_t ret = SenClient.SuspendSensors(pid); @@ -356,7 +356,7 @@ int32_t SensorAgentProxy::ResumeSensors(int32_t pid) const { CALL_LOG_ENTER; if (pid < 0) { - SEN_HILOGE("Pid is invalid, %{public}d", pid); + SEN_HILOGE("Pid is invalid"); return PARAMETER_ERROR; } int32_t ret = SenClient.ResumeSensors(pid); @@ -370,7 +370,7 @@ int32_t SensorAgentProxy::GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **s { CALL_LOG_ENTER; if (pid < 0) { - SEN_HILOGE("Pid is invalid, %{public}d", pid); + SEN_HILOGE("Pid is invalid"); return PARAMETER_ERROR; } CHKPR(subscribeSensorInfos, OHOS::Sensors::ERROR); @@ -387,7 +387,7 @@ int32_t SensorAgentProxy::GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **s return ERROR; } if (subscribeInfoList.empty()) { - SEN_HILOGE("Subscribe info list is empty, pid:%{public}d", pid); + SEN_HILOGE("Subscribe info list is empty"); return ERROR; } size_t subscribeInfoCount = subscribeInfoList.size(); diff --git a/frameworks/native/sensor/src/sensor_data_channel.cpp b/frameworks/native/sensor/src/sensor_data_channel.cpp index 29405216..6b21dfa7 100644 --- a/frameworks/native/sensor/src/sensor_data_channel.cpp +++ b/frameworks/native/sensor/src/sensor_data_channel.cpp @@ -90,7 +90,7 @@ int32_t SensorDataChannel::DestroySensorDataChannel() } if (eventHandler_ != nullptr && listenedFdSet_.empty()) { eventHandler_ = nullptr; - SEN_HILOGI("Set eventHandler_ nullptr"); + SEN_HILOGD("Set eventHandler_ nullptr"); } return DestroySensorBasicChannel(); } @@ -114,7 +114,7 @@ int32_t SensorDataChannel::AddFdListener(int32_t fd, ReceiveMessageFun receiveMe listener->SetChannel(this); auto errCode = eventHandler_->AddFileDescriptorListener(fd, AppExecFwk::FILE_DESCRIPTOR_INPUT_EVENT, listener); if (errCode != ERR_OK) { - SEN_HILOGE("Add fd listener failed, fd:%{public}d, errCode:%{public}u", fd, errCode); + SEN_HILOGE("Add fd listener failed, errCode:%{public}u", errCode); return ERROR; } auto pairRet = listenedFdSet_.insert(fd); @@ -132,13 +132,13 @@ int32_t SensorDataChannel::DelFdListener(int32_t fd) eventHandler_->RemoveFileDescriptorListener(fd); auto it = listenedFdSet_.find(fd); if (it == listenedFdSet_.end()) { - SEN_HILOGE("ListenedFdSet not find fd, fd:%{public}d", fd); + SEN_HILOGE("ListenedFdSet not find fd"); return ERROR; } listenedFdSet_.erase(it); if (eventHandler_ != nullptr && listenedFdSet_.empty()) { eventHandler_ = nullptr; - SEN_HILOGI("Set eventHandler_ nullptr"); + SEN_HILOGD("Set eventHandler_ nullptr"); } return ERR_OK; } diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index 9728f340..315afb81 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -206,7 +206,7 @@ void SensorServiceClient::ProcessDeathObserver(const wptr &object } if (!isConnected_) { - SEN_HILOGI("Previous socket channel status is false, not need retry creat socket channel"); + SEN_HILOGD("Previous socket channel status is false, not need retry creat socket channel"); return; } ReregisterClientInfoCallback(); @@ -442,7 +442,6 @@ void SensorServiceClient::ReregisterClientInfoCallback() return; } isConnected_ = true; - SEN_HILOGI("Client Retry Register Client Info Callback Success"); } } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 4ef9ddcc..e8834055 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -303,7 +303,7 @@ ErrCode SensorServiceProxy::CreateSocketChannel(int32_t &clientFd, const sptr(ret); diff --git a/services/sensor/include/sensor_suspend_policy.h b/services/sensor/include/sensor_suspend_policy.h index 5cf18d38..35769bc8 100644 --- a/services/sensor/include/sensor_suspend_policy.h +++ b/services/sensor/include/sensor_suspend_policy.h @@ -22,13 +22,13 @@ #include "nocopyable.h" -#include "subscribe_info.h" #include "client_info.h" #include "sensor_agent_type.h" #include "sensor_hdi_connection.h" #include "sensor_manager.h" #include "sensors_errors.h" #include "stream_session.h" +#include "subscribe_info.h" namespace OHOS { namespace Sensors { diff --git a/services/sensor/src/client_info.cpp b/services/sensor/src/client_info.cpp index d081932d..18037d30 100644 --- a/services/sensor/src/client_info.cpp +++ b/services/sensor/src/client_info.cpp @@ -690,7 +690,7 @@ int32_t ClientInfo::AddClientInfoCallbackPid(int32_t pid) std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); auto pairRet = clientInfoCallbackPidSet_.insert(pid); if (!pairRet.second) { - SEN_HILOGE("ClientInfoCallbackPidSet_ insert pid fail, pid:%{public}d", pid); + SEN_HILOGE("ClientInfoCallbackPidSet_ insert pid fail"); return ERROR; } return ERR_OK; @@ -701,7 +701,7 @@ int32_t ClientInfo::DelClientInfoCallbackPid(int32_t pid) std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); auto it = clientInfoCallbackPidSet_.find(pid); if (it == clientInfoCallbackPidSet_.end()) { - SEN_HILOGE("ClientInfoCallbackPidSet_ not find pid, pid:%{public}d", pid); + SEN_HILOGE("ClientInfoCallbackPidSet_ not find pid"); return ERROR; } clientInfoCallbackPidSet_.erase(it); @@ -718,13 +718,13 @@ bool ClientInfo::IsUnregisterClientDeathRecipient(int32_t pid) std::lock_guard channelLock(channelMutex_); auto channelIt = channelMap_.find(pid); if (channelIt != channelMap_.end()) { - SEN_HILOGI("pid exist in channelMap, pid:%{public}d", pid); + SEN_HILOGD("pid exist in channelMap"); return false; } std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); auto pidIt = clientInfoCallbackPidSet_.find(pid); if (pidIt != clientInfoCallbackPidSet_.end()) { - SEN_HILOGI("pid exist in clientInfoCallbackPidSet, pid:%{public}d", pid); + SEN_HILOGD("pid exist in clientInfoCallbackPidSet"); return false; } return true; diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 9f34a15b..33a29a61 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -26,8 +26,8 @@ #include "permission_util.h" #include "securec.h" #include "sensor.h" -#include "sensor_dump.h" #include "sensor_agent_type.h" +#include "sensor_dump.h" #include "sensors_errors.h" #include "system_ability_definition.h" @@ -393,11 +393,11 @@ void SensorService::UnregisterClientDeathRecipient(sptr sensorCli CALL_LOG_ENTER; int32_t pid = clientInfo_.FindClientPid(sensorClient); if (pid == INVALID_PID) { - SEN_HILOGE("pid is -1"); + SEN_HILOGE("Pid is invalid"); return; } if (!clientInfo_.IsUnregisterClientDeathRecipient(pid)) { - SEN_HILOGI("Client call other service, not need unregister client death recipient, pid:%{public}d", pid); + SEN_HILOGD("Client call other service, not need unregister client death recipient"); return; } sptr client = iface_cast(sensorClient); @@ -434,12 +434,12 @@ ErrCode SensorService::SuspendSensors(int32_t pid) { CALL_LOG_ENTER; if (pid < 0) { - SEN_HILOGE("Pid is invalid, pid:%{public}d", pid); + SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } int32_t ret = suspendPolicy_.DoSuspend(pid); if (ret != ERR_OK) { - SEN_HILOGE("Suspend pid sensors failed, pid:%{public}d", pid); + SEN_HILOGE("Suspend pid sensors failed"); return ERROR; } return ERR_OK; @@ -449,12 +449,12 @@ ErrCode SensorService::ResumeSensors(int32_t pid) { CALL_LOG_ENTER; if (pid < 0) { - SEN_HILOGE("Pid is invalid, pid:%{public}d", pid); + SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } int32_t ret = suspendPolicy_.DoResume(pid); if (ret != ERR_OK) { - SEN_HILOGE("Resume pid sensors failed, pid:%{public}d", pid); + SEN_HILOGE("Resume pid sensors failed"); return ERROR; } return ERR_OK; @@ -464,12 +464,12 @@ ErrCode SensorService::GetSubscribeInfoList(int32_t pid, std::vector SensorInfoMap = pidSensorInfoIt->second; if (!DisableSensorList(SensorInfoMap, sensorIdList, pid)) { SEN_HILOGE("Some sensor disable failed"); @@ -54,7 +54,7 @@ ErrCode SensorSuspendPolicy::DoSuspend(int32_t pid) } } if (sensorIdList.empty()) { - SEN_HILOGE("Pid sensorId list is empty, pid: %{public}d", pid); + SEN_HILOGE("Pid sensorId list is empty"); return ERROR; } std::unordered_map SensorInfoMap; @@ -78,8 +78,7 @@ bool SensorSuspendPolicy::DisableSensorList(std::unordered_map pidSensorInfoLock(pidSensorInfoMutex_); auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); if (pidSensorInfoIt == pidSensorInfoMap_.end()) { - SEN_HILOGE("Pid not have suspend sensors, pid: %{public}d", pid); + SEN_HILOGE("Pid not have suspend sensors"); return ERROR; } bool resumeAllSensors = true; @@ -125,8 +124,7 @@ ErrCode SensorSuspendPolicy::DoResume(int32_t pid) int64_t maxReportDelayNs = sensorIt->second.GetMaxReportDelayNs(); auto ret = EnableSensor(sensorId, pid, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { - SEN_HILOGE("Enable Sensor is failed. sensorId: %{public}u, pid: %{public}d, ret: %{public}d", - sensorId, pid, ret); + SEN_HILOGE("Enable Sensor is failed. sensorId:%{public}d, ret:%{public}d", sensorId, ret); resumeAllSensors = false; ++sensorIt; } else { @@ -151,15 +149,12 @@ ErrCode SensorSuspendPolicy::EnableSensor(int32_t sensorId, int32_t pid, int64_t return ERR_NO_INIT; } if (clientInfo_.GetSensorState(sensorId)) { - SEN_HILOGW("Sensor has been enabled already, sensorId: %{public}d", sensorId); + SEN_HILOGD("Sensor has been enabled already, sensorId: %{public}d", sensorId); auto ret = RestoreSensorInfo(sensorId, pid, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { SEN_HILOGE("RestoreSensorInfo is failed, ret: %{public}d", ret); return ret; } - if (ret != ERR_OK) { - SEN_HILOGE("FlushProcess is failed, ret: %{public}d", ret); - } return ERR_OK; } auto ret = RestoreSensorInfo(sensorId, pid, samplingPeriodNs, maxReportDelayNs); @@ -239,7 +234,7 @@ void SensorSuspendPolicy::ReportClientInfo(SubscribeSensorInfo subscribeSensorIn } for (auto sess : sessionList) { if (!sess->SendMsg(pkt)) { - SEN_HILOGE("Packet send failed, pid:%{public}d", sess->GetPid()); + SEN_HILOGE("Packet send failed"); continue; } } diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index a93b676f..31399c25 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -44,13 +44,12 @@ bool StreamServer::SendMsg(int32_t fd, NetPacket& pkt) { CALL_LOG_ENTER; if (fd < 0) { - SEN_HILOGE("The fd is less than 0"); + SEN_HILOGE("Fd is invalid"); return false; } auto ses = GetSession(fd); if (ses == nullptr) { - SEN_HILOGE("The fd:%{public}d not found, The message was discarded. errCode:%{public}d", - fd, PROTO_SESSION_NOT_FOUND); + SEN_HILOGE("Fd not found, The message was discarded. errCode:%{public}d", PROTO_SESSION_NOT_FOUND); return false; } return ses->SendMsg(pkt); @@ -89,7 +88,7 @@ SessionPtr StreamServer::GetSession(int32_t fd) std::lock_guard sessionLock(sessionMutex_); auto it = sessionsMap_.find(fd); if (it == sessionsMap_.end()) { - SEN_HILOGE("Session not found.fd:%{public}d", fd); + SEN_HILOGE("Session not found"); return nullptr; } CHKPP(it->second); @@ -100,7 +99,7 @@ SessionPtr StreamServer::GetSessionByPid(int32_t pid) { int32_t fd = GetClientFd(pid); if (fd <= 0) { - SEN_HILOGE("Session not found.pid:%{public}d", pid); + SEN_HILOGE("Session not found"); return nullptr; } return GetSession(fd); @@ -175,7 +174,7 @@ bool StreamServer::AddSession(SessionPtr ses) CHKPF(ses); auto fd = ses->GetFd(); if (fd < 0) { - SEN_HILOGE("The fd is less than 0"); + SEN_HILOGE("Fd is Invalid"); return false; } auto pid = ses->GetPid(); @@ -188,23 +187,11 @@ bool StreamServer::AddSession(SessionPtr ses) PROTO_MAX_SESSON_ALARM, sessionsMap_.size()); return false; } - DelSession(pid); std::lock_guard idxPidLock(idxPidMutex_); idxPidMap_[pid] = fd; std::lock_guard sessionLock(sessionMutex_); sessionsMap_[fd] = ses; - - SEN_HILOGI("************AddSession()************"); - SEN_HILOGI("******idxPidMap_ size is %{public}zu******", idxPidMap_.size()); - for (auto it = idxPidMap_.begin(); it != idxPidMap_.end(); it++) { - SEN_HILOGI("******pid:%{public}d, fd:%{public}d******", it->first, it->second); - } - SEN_HILOGI("******sessionsMap_ size is %{public}zu******", sessionsMap_.size()); - for (auto it = sessionsMap_.begin(); it != sessionsMap_.end(); it++) { - SEN_HILOGI("******fd:%{public}d, programName:%{public}s, moduleType:%{public}d, fd:%{public}d, uid:%{public}d, pid:%{public}d", - it->first, it->second->GetProgramName().c_str(), it->second->GetModuleType(), it->second->GetFd(), it->second->GetUid(), it->second->GetPid()); - } return true; } @@ -226,20 +213,9 @@ void StreamServer::DelSession(int32_t pid) if (fd >= 0) { auto rf = close(fd); if (rf > 0) { - SEN_HILOGE("Socket fd close failed, fd:%{public}d, rf:%{public}d", fd, rf); + SEN_HILOGE("Socket fd close failed, rf:%{public}d", rf); } } - - SEN_HILOGI("************DelSession()************"); - SEN_HILOGI("******idxPidMap_ size is %{public}zu******", idxPidMap_.size()); - for (auto it = idxPidMap_.begin(); it != idxPidMap_.end(); it++) { - SEN_HILOGI("******pid:%{public}d, fd:%{public}d******", it->first, it->second); - } - SEN_HILOGI("******sessionsMap_ size is %{public}zu******", sessionsMap_.size()); - for (auto it = sessionsMap_.begin(); it != sessionsMap_.end(); it++) { - SEN_HILOGI("******fd:%{public}d, programName:%{public}s, moduleType:%{public}d, fd:%{public}d, uid:%{public}d, pid:%{public}d", - it->first, it->second->GetProgramName().c_str(), it->second->GetModuleType(), it->second->GetFd(), it->second->GetUid(), it->second->GetPid()); - } } } // namespace Sensors } // namespace OHOS \ No newline at end of file -- Gitee From 5a496cc30e0c35e7b2552fd645a64bab89f2b93f Mon Sep 17 00:00:00 2001 From: hui1975 Date: Sat, 4 Mar 2023 10:20:49 +0000 Subject: [PATCH 04/53] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: I5e9d8c87c43ec74941ce008d0dd5f4f39290e35f --- .../native/sensor/src/sensor_agent_proxy.cpp | 2 +- .../native/sensor/src/sensor_data_channel.cpp | 4 +-- .../sensor/src/sensor_service_client.cpp | 19 +++--------- interfaces/native/include/sensor_agent_type.h | 2 +- .../test/unittest/sensor_power_test.cpp | 31 +++++++------------ services/sensor/include/sensor_service.h | 2 +- services/sensor/src/sensor_service.cpp | 12 +++---- 7 files changed, 28 insertions(+), 44 deletions(-) diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index 7bb938a7..f7aeffd3 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -392,7 +392,7 @@ int32_t SensorAgentProxy::GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **s } size_t subscribeInfoCount = subscribeInfoList.size(); if (subscribeInfoCount > MAX_SENSOR_LIST_SIZE) { - SEN_HILOGE("The number of subscribe info exceeds the maximum value, count:%{public}d", subscribeInfoCount); + SEN_HILOGE("The number of subscribe info exceeds the maximum value, count:%{public}zu", subscribeInfoCount); return ERROR; } subscribeSensorInfos_ = (SubscribeSensorInfo *)malloc(sizeof(SubscribeSensorInfo) * subscribeInfoCount); diff --git a/frameworks/native/sensor/src/sensor_data_channel.cpp b/frameworks/native/sensor/src/sensor_data_channel.cpp index 6b21dfa7..cc640755 100644 --- a/frameworks/native/sensor/src/sensor_data_channel.cpp +++ b/frameworks/native/sensor/src/sensor_data_channel.cpp @@ -88,7 +88,7 @@ int32_t SensorDataChannel::DestroySensorDataChannel() if (it != listenedFdSet_.end()) { listenedFdSet_.erase(it); } - if (eventHandler_ != nullptr && listenedFdSet_.empty()) { + if (listenedFdSet_.empty() && eventHandler_ != nullptr) { eventHandler_ = nullptr; SEN_HILOGD("Set eventHandler_ nullptr"); } @@ -136,7 +136,7 @@ int32_t SensorDataChannel::DelFdListener(int32_t fd) return ERROR; } listenedFdSet_.erase(it); - if (eventHandler_ != nullptr && listenedFdSet_.empty()) { + if (listenedFdSet_.empty() && eventHandler_ != nullptr) { eventHandler_ = nullptr; SEN_HILOGD("Set eventHandler_ nullptr"); } diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index 315afb81..bb69fdae 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -293,16 +293,11 @@ int32_t SensorServiceClient::RegisterClientInfoCallback(ClientInfoCallback callb StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel"); ret = sensorServer_->CreateSocketChannel(clientFd, sensorClientStub_); FinishTrace(HITRACE_TAG_SENSORS); - if (ret != ERR_OK) { + if (!(ret == ERR_OK && clientFd >= 0)) { Close(); SEN_HILOGE("Create socket channel failed"); return ret; } - if (clientFd < 0) { - Close(); - SEN_HILOGE("socketFd is invalid"); - return ERROR; - } fd_ = clientFd; dataChannel_ = sensorDataChannel; if (dataChannel_->AddFdListener(fd_, @@ -335,7 +330,6 @@ int32_t SensorServiceClient::UnregisterClientInfoCallback(ClientInfoCallback cal if (!clientInfoCallbackSet_.empty()) { return ERR_OK; } - Disconnect(); int32_t ret = InitServiceClient(); if (ret != ERR_OK) { SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); @@ -349,6 +343,7 @@ int32_t SensorServiceClient::UnregisterClientInfoCallback(ClientInfoCallback cal SEN_HILOGE("Disable clientInfo callback failed"); return ret; } + Disconnect(); StartTrace(HITRACE_TAG_SENSORS, "DestroySocketChannel"); ret = sensorServer_->DestroySocketChannel(sensorClientStub_); FinishTrace(HITRACE_TAG_SENSORS); @@ -389,7 +384,7 @@ void SensorServiceClient::HandleNetPacke(NetPacket &pkt) std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); for (auto callback : clientInfoCallbackSet_) { if (callback != nullptr) { - callback(&subscribeSensorInfo); + callback(subscribeSensorInfo); } } } @@ -400,6 +395,7 @@ void SensorServiceClient::Disconnect() if (fd_ < 0) { return; } + CHKPV(dataChannel_); int32_t ret = dataChannel_->DelFdListener(fd_); if (ret != ERR_OK) { SEN_HILOGE("Delete fd listener failed"); @@ -415,16 +411,11 @@ void SensorServiceClient::ReregisterClientInfoCallback() StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel"); int32_t ret = sensorServer_->CreateSocketChannel(clientFd, sensorClientStub_); FinishTrace(HITRACE_TAG_SENSORS); - if (ret != ERR_OK) { + if (!(ret == ERR_OK && clientFd >= 0)) { Close(); SEN_HILOGE("Create socket channel failed"); return; } - if (clientFd < 0) { - Close(); - SEN_HILOGE("socketFd is invalid"); - return; - } fd_ = clientFd; if (dataChannel_->AddFdListener(fd_, std::bind(&SensorServiceClient::ReceiveMessage, this, std::placeholders::_1, std::placeholders::_2), diff --git a/interfaces/native/include/sensor_agent_type.h b/interfaces/native/include/sensor_agent_type.h index b298ad0d..9448f98c 100644 --- a/interfaces/native/include/sensor_agent_type.h +++ b/interfaces/native/include/sensor_agent_type.h @@ -403,7 +403,7 @@ typedef struct SubscribeSensorInfo { int64_t maxReportDelayNs = -1; /**< Maximum Report Delay, in ns */ } SubscribeSensorInfo; -typedef void (*ClientInfoCallback)(SubscribeSensorInfo *subscribeSensorInfo); +typedef void (*ClientInfoCallback)(SubscribeSensorInfo &subscribeSensorInfo); #ifdef __cplusplus #if __cplusplus diff --git a/interfaces/native/test/unittest/sensor_power_test.cpp b/interfaces/native/test/unittest/sensor_power_test.cpp index bfb4bc1f..da5a3dfb 100644 --- a/interfaces/native/test/unittest/sensor_power_test.cpp +++ b/interfaces/native/test/unittest/sensor_power_test.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ +#include #include #include @@ -90,28 +91,20 @@ void SensorDataCallbackImpl(SensorEvent *event) event[0].sensorTypeId, event[0].version, event[0].dataLen, *(sensorData)); } -void ClientInfoCallbackImpl(SubscribeSensorInfo *subscribeSensorInfo) +void ClientInfoCallbackImpl(SubscribeSensorInfo &subscribeSensorInfo) { - if (subscribeSensorInfo == nullptr) { - SEN_HILOGE("subscribeSensorInfo is null"); - return; - } SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " - "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", - subscribeSensorInfo->pid, subscribeSensorInfo->sensorId, subscribeSensorInfo->isActive, - subscribeSensorInfo->samplingPeriodNs, subscribeSensorInfo->maxReportDelayNs); + "samplingPeriodNs:%{public}" PRId64 ", maxReportDelayNs:%{public}" PRId64 "", + subscribeSensorInfo.pid, subscribeSensorInfo.sensorId, subscribeSensorInfo.isActive, + subscribeSensorInfo.samplingPeriodNs, subscribeSensorInfo.maxReportDelayNs); } -void ClientInfoCallbackImpl2(SubscribeSensorInfo *subscribeSensorInfo) +void ClientInfoCallbackImpl2(SubscribeSensorInfo &subscribeSensorInfo) { - if (subscribeSensorInfo == nullptr) { - SEN_HILOGE("subscribeSensorInfo is null"); - return; - } SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " - "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", - subscribeSensorInfo->pid, subscribeSensorInfo->sensorId, subscribeSensorInfo->isActive, - subscribeSensorInfo->samplingPeriodNs, subscribeSensorInfo->maxReportDelayNs); + "samplingPeriodNs:%{public}" PRId64 ", maxReportDelayNs:%{public}" PRId64 "", + subscribeSensorInfo.pid, subscribeSensorInfo.sensorId, subscribeSensorInfo.isActive, + subscribeSensorInfo.samplingPeriodNs, subscribeSensorInfo.maxReportDelayNs); } HWTEST_F(SensorPowerTest, SuspendSensorsTest_001, TestSize.Level1) @@ -179,7 +172,7 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_001, TestSize.Level1) for (int32_t i = 0; i < count; ++i) { SubscribeSensorInfo *curSubscribeSensorInfo = subscribeSensorInfo + i; SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " - "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", + "samplingPeriodNs:%{public}" PRId64 ", maxReportDelayNs:%{public}" PRId64 "", i, curSubscribeSensorInfo->pid, curSubscribeSensorInfo->sensorId, curSubscribeSensorInfo->isActive, curSubscribeSensorInfo->samplingPeriodNs, curSubscribeSensorInfo->maxReportDelayNs); } @@ -224,7 +217,7 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_002, TestSize.Level1) for (int32_t i = 0; i < count; ++i) { SubscribeSensorInfo *curSubscribeSensorInfo = subscribeSensorInfo + i; SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " - "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", + "samplingPeriodNs:%{public}" PRId64 ", maxReportDelayNs:%{public}" PRId64 "", i, curSubscribeSensorInfo->pid, curSubscribeSensorInfo->sensorId, curSubscribeSensorInfo->isActive, curSubscribeSensorInfo->samplingPeriodNs, curSubscribeSensorInfo->maxReportDelayNs); } @@ -269,7 +262,7 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_003, TestSize.Level1) for (int32_t i = 0; i < count; ++i) { SubscribeSensorInfo *curSubscribeSensorInfo = subscribeSensorInfo + i; SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " - "samplingPeriodNs:%{public}lld, maxReportDelayNs:%{public}lld", + "samplingPeriodNs:%{public}" PRId64 ", maxReportDelayNs:%{public}" PRId64 "", i, curSubscribeSensorInfo->pid, curSubscribeSensorInfo->sensorId, curSubscribeSensorInfo->isActive, curSubscribeSensorInfo->samplingPeriodNs, curSubscribeSensorInfo->maxReportDelayNs); } diff --git a/services/sensor/include/sensor_service.h b/services/sensor/include/sensor_service.h index 68ce80bd..ccd7a65b 100644 --- a/services/sensor/include/sensor_service.h +++ b/services/sensor/include/sensor_service.h @@ -93,7 +93,7 @@ private: sptr clientDeathObserver_ = nullptr; ErrCode SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); - std::atomic_bool IsReportClientInfo_ = false; + std::atomic_bool isReportClientInfo_ = false; void ReportClientInfo(int32_t sensorId, bool isActive, int32_t pid); }; } // namespace Sensors diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 33a29a61..78f4dcc9 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -235,7 +235,7 @@ ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, SEN_HILOGE("ret : %{public}d", ret); } ReportOnChangeData(sensorId); - if (IsReportClientInfo_) { + if (isReportClientInfo_) { ReportClientInfo(sensorId, true, pid); } return ERR_OK; @@ -253,7 +253,7 @@ ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, return ENABLE_SENSOR_ERR; } ReportSensorSysEvent(sensorId, true, pid); - if (IsReportClientInfo_) { + if (isReportClientInfo_) { ReportClientInfo(sensorId, true, pid); } return ret; @@ -274,7 +274,7 @@ ErrCode SensorService::DisableSensor(int32_t sensorId, int32_t pid) std::lock_guard serviceLock(serviceLock_); if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { SEN_HILOGW("other client is using this sensor now, cannot disable"); - if (IsReportClientInfo_) { + if (isReportClientInfo_) { ReportClientInfo(sensorId, false, pid); } return ERR_OK; @@ -286,7 +286,7 @@ ErrCode SensorService::DisableSensor(int32_t sensorId, int32_t pid) int32_t uid = clientInfo_.GetUidByPid(pid); clientInfo_.DestroyCmd(uid); clientInfo_.ClearDataQueue(sensorId); - if (IsReportClientInfo_) { + if (isReportClientInfo_) { ReportClientInfo(sensorId, false, pid); } return sensorManager_.AfterDisableSensor(sensorId); @@ -504,7 +504,7 @@ ErrCode SensorService::DestroySocketChannel(const sptr &sensorCli ErrCode SensorService::EnableClientInfoCallback() { CALL_LOG_ENTER; - IsReportClientInfo_ = true; + isReportClientInfo_ = true; int32_t pid = GetCallingPid(); return clientInfo_.AddClientInfoCallbackPid(pid); } @@ -512,7 +512,7 @@ ErrCode SensorService::EnableClientInfoCallback() ErrCode SensorService::DisableClientInfoCallback() { CALL_LOG_ENTER; - IsReportClientInfo_ = false; + isReportClientInfo_ = false; int32_t pid = GetCallingPid(); return clientInfo_.DelClientInfoCallbackPid(pid); } -- Gitee From 26040e1922d3bacb80a508524289f6eea01876f3 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 6 Mar 2023 06:05:37 +0000 Subject: [PATCH 05/53] =?UTF-8?q?sensor=E7=9C=81=E5=8A=9F=E8=80=97?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: I66bc0001731d09e7caa0569054aafdb840855126 --- .../sensor/include/sensor_service_client.h | 2 +- .../native/sensor/src/sensor_agent_proxy.cpp | 4 +- .../sensor/src/sensor_service_client.cpp | 65 +++++++------------ interfaces/native/src/sensor_agent.cpp | 6 +- services/sensor/src/sensor_service.cpp | 8 +-- 5 files changed, 34 insertions(+), 51 deletions(-) diff --git a/frameworks/native/sensor/include/sensor_service_client.h b/frameworks/native/sensor/include/sensor_service_client.h index ea17de0b..21ff9837 100755 --- a/frameworks/native/sensor/include/sensor_service_client.h +++ b/frameworks/native/sensor/include/sensor_service_client.h @@ -68,8 +68,8 @@ private: std::mutex mapMutex_; std::map sensorInfoMap_; + int32_t CreateSocketChannel(); void HandleNetPacke(NetPacket &pkt); - void ReregisterClientInfoCallback(); std::atomic_bool isConnected_ = false; CircleStreamBuffer circBuf_; diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index f7aeffd3..7438e442 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -416,7 +416,7 @@ int32_t SensorAgentProxy::RegisterClientInfoCallback(ClientInfoCallback callback CHKPR(dataChannel_, INVALID_POINTER); int32_t ret = SenClient.RegisterClientInfoCallback(callback, dataChannel_); if (ret != ERR_OK) { - SEN_HILOGE("RegisterClientInfoCallback failed"); + SEN_HILOGE("Register client info callback failed, ret:%{public}d", ret); } return SUCCESS; } @@ -426,7 +426,7 @@ int32_t SensorAgentProxy::UnregisterClientInfoCallback(ClientInfoCallback callba CHKPR(callback, OHOS::Sensors::ERROR); int32_t ret = SenClient.UnregisterClientInfoCallback(callback); if (ret != ERR_OK) { - SEN_HILOGE("UnregisterClientInfoCallback failed"); + SEN_HILOGE("Unregister client info callback failed, ret:%{public}d, ret", ret); } return SUCCESS; } diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index bb69fdae..2979dfc6 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -209,7 +209,8 @@ void SensorServiceClient::ProcessDeathObserver(const wptr &object SEN_HILOGD("Previous socket channel status is false, not need retry creat socket channel"); return; } - ReregisterClientInfoCallback(); + Disconnect(); + CreateSocketChannel(); } void SensorServiceClient::UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay) @@ -282,40 +283,15 @@ int32_t SensorServiceClient::GetSubscribeInfoList(int32_t pid, std::vector sensorDataChannel) { CALL_LOG_ENTER; + if (!isConnected_) { - int32_t ret = InitServiceClient(); - if (ret != ERR_OK) { - SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); - return ret; - } - CHKPR(sensorServer_, ERROR); - int32_t clientFd = -1; - StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel"); - ret = sensorServer_->CreateSocketChannel(clientFd, sensorClientStub_); - FinishTrace(HITRACE_TAG_SENSORS); - if (!(ret == ERR_OK && clientFd >= 0)) { - Close(); - SEN_HILOGE("Create socket channel failed"); - return ret; - } - fd_ = clientFd; + CHKPR(sensorDataChannel, INVALID_POINTER); dataChannel_ = sensorDataChannel; - if (dataChannel_->AddFdListener(fd_, - std::bind(&SensorServiceClient::ReceiveMessage, this, std::placeholders::_1, std::placeholders::_2), - std::bind(&SensorServiceClient::Disconnect, this)) != ERR_OK) { - Close(); - SEN_HILOGE("Add fd listener failed"); - return ERROR; - } - StartTrace(HITRACE_TAG_SENSORS, "EnableClientInfoCallback"); - ret = sensorServer_->EnableClientInfoCallback(); - FinishTrace(HITRACE_TAG_SENSORS); + int32_t ret = CreateSocketChannel(); if (ret != ERR_OK) { - SEN_HILOGE("Enable clientInfo callback failed"); - Disconnect(); + SEN_HILOGE("Register client info callback failed, ret:%{public}d", ret); return ret; } - isConnected_ = true; } std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); clientInfoCallbackSet_.insert(callback); @@ -340,7 +316,7 @@ int32_t SensorServiceClient::UnregisterClientInfoCallback(ClientInfoCallback cal ret = sensorServer_->DisableClientInfoCallback(); FinishTrace(HITRACE_TAG_SENSORS); if (ret != ERR_OK) { - SEN_HILOGE("Disable clientInfo callback failed"); + SEN_HILOGE("Disable clientInfo callback failed, ret:%{public}d", ret); return ret; } Disconnect(); @@ -348,7 +324,7 @@ int32_t SensorServiceClient::UnregisterClientInfoCallback(ClientInfoCallback cal ret = sensorServer_->DestroySocketChannel(sensorClientStub_); FinishTrace(HITRACE_TAG_SENSORS); if (ret != ERR_OK) { - SEN_HILOGE("Destroy socket channel failed"); + SEN_HILOGE("Destroy socket channel failed, ret:%{public}d", ret); return ret; } isConnected_ = false; @@ -372,6 +348,7 @@ void SensorServiceClient::HandleNetPacke(NetPacket &pkt) { auto id = pkt.GetMsgId(); if (id != MessageId::CLIENT_INFO) { + SEN_HILOGE("NetPacke message id is not CLIENT_INFO"); return; } SubscribeSensorInfo subscribeSensorInfo; @@ -398,23 +375,28 @@ void SensorServiceClient::Disconnect() CHKPV(dataChannel_); int32_t ret = dataChannel_->DelFdListener(fd_); if (ret != ERR_OK) { - SEN_HILOGE("Delete fd listener failed"); + SEN_HILOGE("Delete fd listener failed, ret:%{public}d", ret); } Close(); } -void SensorServiceClient::ReregisterClientInfoCallback() +int32_t SensorServiceClient::CreateSocketChannel() { CALL_LOG_ENTER; - Disconnect(); + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return ret; + } + CHKPR(sensorServer_, ERROR); int32_t clientFd = -1; StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel"); - int32_t ret = sensorServer_->CreateSocketChannel(clientFd, sensorClientStub_); + ret = sensorServer_->CreateSocketChannel(clientFd, sensorClientStub_); FinishTrace(HITRACE_TAG_SENSORS); if (!(ret == ERR_OK && clientFd >= 0)) { Close(); - SEN_HILOGE("Create socket channel failed"); - return; + SEN_HILOGE("Create socket channel failed, ret:%{public}d", ret); + return ret; } fd_ = clientFd; if (dataChannel_->AddFdListener(fd_, @@ -422,17 +404,18 @@ void SensorServiceClient::ReregisterClientInfoCallback() std::bind(&SensorServiceClient::Disconnect, this)) != ERR_OK) { Close(); SEN_HILOGE("Add fd listener failed"); - return; + return ERROR; } StartTrace(HITRACE_TAG_SENSORS, "EnableClientInfoCallback"); ret = sensorServer_->EnableClientInfoCallback(); FinishTrace(HITRACE_TAG_SENSORS); if (ret != ERR_OK) { - SEN_HILOGE("Enable clientInfo callback failed"); + SEN_HILOGE("Enable clientInfo callback failed, ret:%{public}d", ret); Disconnect(); - return; + return ret; } isConnected_ = true; + return ERR_OK; } } // namespace Sensors } // namespace OHOS diff --git a/interfaces/native/src/sensor_agent.cpp b/interfaces/native/src/sensor_agent.cpp index 559abc89..9c400650 100755 --- a/interfaces/native/src/sensor_agent.cpp +++ b/interfaces/native/src/sensor_agent.cpp @@ -189,7 +189,7 @@ int32_t GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **subscribeSensorInfo } int32_t ret = proxy->GetSubscribeInfos(pid, subscribeSensorInfos, count); if (ret != OHOS::ERR_OK) { - SEN_HILOGE("GetSubscribeInfos failed, ret:%{public}d", ret); + SEN_HILOGE("Get subscribe Infos failed, ret:%{public}d", ret); return NormalizeErrCode(ret); } return ret; @@ -204,7 +204,7 @@ int32_t RegisterClientInfoCallback(ClientInfoCallback callback) } int32_t ret = proxy->RegisterClientInfoCallback(callback); if (ret != OHOS::ERR_OK) { - SEN_HILOGE("RegisterClientInfoCallback failed"); + SEN_HILOGE("Register client info callback failed, ret:%{public}d", ret); return NormalizeErrCode(ret); } return ret; @@ -219,7 +219,7 @@ int32_t UnregisterClientInfoCallback(ClientInfoCallback callback) } int32_t ret = proxy->UnregisterClientInfoCallback(callback); if (ret != OHOS::ERR_OK) { - SEN_HILOGE("UnregisterClientInfoCallback failed"); + SEN_HILOGE("Unregister client info callback failed, ret:%{public}d", ret); return NormalizeErrCode(ret); } return ret; diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 78f4dcc9..e98885d1 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -439,7 +439,7 @@ ErrCode SensorService::SuspendSensors(int32_t pid) } int32_t ret = suspendPolicy_.DoSuspend(pid); if (ret != ERR_OK) { - SEN_HILOGE("Suspend pid sensors failed"); + SEN_HILOGE("Suspend pid sensors failed, ret:%{public}d", ret); return ERROR; } return ERR_OK; @@ -454,7 +454,7 @@ ErrCode SensorService::ResumeSensors(int32_t pid) } int32_t ret = suspendPolicy_.DoResume(pid); if (ret != ERR_OK) { - SEN_HILOGE("Resume pid sensors failed"); + SEN_HILOGE("Resume pid sensors failed, ret:%{public}d", ret); return ERROR; } return ERR_OK; @@ -469,7 +469,7 @@ ErrCode SensorService::GetSubscribeInfoList(int32_t pid, std::vector Date: Mon, 6 Mar 2023 08:42:52 +0000 Subject: [PATCH 06/53] =?UTF-8?q?=E9=87=8D=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: I548296b2bff18bdd1d0e6a3ed665c36939fe73e6 --- .../native/sensor/include/i_sensor_service.h | 14 +-- .../sensor/include/sensor_agent_proxy.h | 6 +- .../sensor/include/sensor_service_client.h | 14 ++- .../sensor/include/sensor_service_proxy.h | 6 +- .../native/sensor/src/sensor_agent_proxy.cpp | 91 +++++++++---------- .../sensor/src/sensor_service_client.cpp | 47 +++++----- .../sensor/src/sensor_service_proxy.cpp | 36 ++++---- interfaces/native/include/sensor_agent.h | 16 ++-- interfaces/native/include/sensor_agent_type.h | 7 +- interfaces/native/src/sensor_agent.cpp | 24 ++--- services/sensor/include/client_info.h | 10 +- services/sensor/include/sensor_service.h | 10 +- services/sensor/include/sensor_service_stub.h | 6 +- .../sensor/include/sensor_suspend_policy.h | 10 +- services/sensor/src/client_info.cpp | 32 +++---- services/sensor/src/sensor_service.cpp | 65 ++++--------- services/sensor/src/sensor_service_stub.cpp | 32 +++---- services/sensor/src/sensor_suspend_policy.cpp | 38 ++------ utils/common/BUILD.gn | 2 +- .../{subscribe_info.h => active_info.h} | 21 ++--- .../{subscribe_info.cpp => active_info.cpp} | 66 +++++--------- 21 files changed, 238 insertions(+), 315 deletions(-) rename utils/common/include/{subscribe_info.h => active_info.h} (73%) rename utils/common/src/{subscribe_info.cpp => active_info.cpp} (52%) diff --git a/frameworks/native/sensor/include/i_sensor_service.h b/frameworks/native/sensor/include/i_sensor_service.h index d6da491e..d8ca66e7 100755 --- a/frameworks/native/sensor/include/i_sensor_service.h +++ b/frameworks/native/sensor/include/i_sensor_service.h @@ -21,10 +21,10 @@ #include "errors.h" #include "iremote_broker.h" +#include "active_info.h" #include "i_sensor_client.h" #include "sensor_basic_data_channel.h" #include "sensor.h" -#include "subscribe_info.h" namespace OHOS { namespace Sensors { @@ -42,11 +42,11 @@ public: virtual ErrCode DestroySensorChannel(sptr sensorClient) = 0; virtual ErrCode SuspendSensors(int32_t pid) = 0; virtual ErrCode ResumeSensors(int32_t pid) = 0; - virtual ErrCode GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) = 0; + virtual ErrCode GetActiveInfoList(int32_t pid, std::vector &activeInfoList) = 0; virtual ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) = 0; virtual ErrCode DestroySocketChannel(const sptr &sensorClient) = 0; - virtual ErrCode EnableClientInfoCallback() = 0; - virtual ErrCode DisableClientInfoCallback() = 0; + virtual ErrCode EnableActiveInfoCB() = 0; + virtual ErrCode DisableActiveInfoCB() = 0; enum { ENABLE_SENSOR = 0, DISABLE_SENSOR, @@ -57,11 +57,11 @@ public: DESTROY_SENSOR_CHANNEL, SUSPEND_SENSORS, RESUME_SENSORS, - GET_SUBSCRIBE_INFO_LIST, + GET_ACTIVE_INFO_LIST, CREATE_SOCKET_CHANNEL, DESTROY_SOCKET_CHANNEL, - ENABLE_CLIENT_INFO_CALLBACK, - DISABLE_CLIENT_INFO_CALLBACK, + ENABLE_ACTIVE_INFO_CB, + DISABLE_ACTIVE_INFO_CB, }; }; } // namespace Sensors diff --git a/frameworks/native/sensor/include/sensor_agent_proxy.h b/frameworks/native/sensor/include/sensor_agent_proxy.h index ddb0684e..4e36e6eb 100644 --- a/frameworks/native/sensor/include/sensor_agent_proxy.h +++ b/frameworks/native/sensor/include/sensor_agent_proxy.h @@ -45,9 +45,9 @@ public: int32_t GetAllSensors(SensorInfo **sensorInfo, int32_t *count) const; int32_t SuspendSensors(int32_t pid) const; int32_t ResumeSensors(int32_t pid) const; - int32_t GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **subscribeSensorInfos, int32_t *count) const; - int32_t RegisterClientInfoCallback(ClientInfoCallback callback) const; - int32_t UnregisterClientInfoCallback(ClientInfoCallback callback) const; + int32_t GetSensorActiveInfos(int32_t pid, SensorActiveInfo **sensorActiveInfos, int32_t *count) const; + int32_t RegisterSensorActiveInfoCB(SensorActiveInfoCB callback) const; + int32_t UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback) const; private: int32_t CreateSensorDataChannel() const; diff --git a/frameworks/native/sensor/include/sensor_service_client.h b/frameworks/native/sensor/include/sensor_service_client.h index 21ff9837..85207e98 100755 --- a/frameworks/native/sensor/include/sensor_service_client.h +++ b/frameworks/native/sensor/include/sensor_service_client.h @@ -23,6 +23,7 @@ #include "iservice_registry.h" #include "singleton.h" +#include "active_info.h" #include "sensor_agent_type.h" #include "sensor_basic_data_channel.h" #include "sensor_basic_info.h" @@ -31,7 +32,6 @@ #include "sensor.h" #include "sensor_service_proxy.h" #include "stream_socket.h" -#include "subscribe_info.h" namespace OHOS { namespace Sensors { @@ -47,11 +47,9 @@ public: bool IsValid(int32_t sensorId); int32_t SuspendSensors(int32_t pid); int32_t ResumeSensors(int32_t pid); - int32_t GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList); - - int32_t RegisterClientInfoCallback(ClientInfoCallback callback, sptr sensorDataChannel); - int32_t UnregisterClientInfoCallback(ClientInfoCallback callback); - + int32_t GetActiveInfoList(int32_t pid, std::vector &activeInfoList); + int32_t RegisterSensorActiveInfoCB(SensorActiveInfoCB callback, sptr sensorDataChannel); + int32_t UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback); void ReceiveMessage(const char *buf, size_t size); void Disconnect(); @@ -73,8 +71,8 @@ private: std::atomic_bool isConnected_ = false; CircleStreamBuffer circBuf_; - std::mutex clientInfoCallbackMutex_; - std::set clientInfoCallbackSet_; + std::mutex activeInfoCBMutex_; + std::set activeInfoCBSet_; }; } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/sensor/include/sensor_service_proxy.h b/frameworks/native/sensor/include/sensor_service_proxy.h index 49523092..59f5a375 100755 --- a/frameworks/native/sensor/include/sensor_service_proxy.h +++ b/frameworks/native/sensor/include/sensor_service_proxy.h @@ -37,11 +37,11 @@ public: ErrCode DestroySensorChannel(sptr sensorClient) override; ErrCode SuspendSensors(int32_t pid) override; ErrCode ResumeSensors(int32_t pid) override; - ErrCode GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) override; + ErrCode GetActiveInfoList(int32_t pid, std::vector &activeInfoList) override; ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) override; ErrCode DestroySocketChannel(const sptr &sensorClient) override; - ErrCode EnableClientInfoCallback() override; - ErrCode DisableClientInfoCallback() override; + ErrCode EnableActiveInfoCB() override; + ErrCode DisableActiveInfoCB() override; private: DISALLOW_COPY_AND_MOVE(SensorServiceProxy); diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index 7438e442..ebf42acc 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -39,8 +39,8 @@ std::recursive_mutex SensorAgentProxy::subscribeMutex_; std::mutex SensorAgentProxy::chanelMutex_; std::mutex sensorInfoMutex_; SensorInfo *sensorInfos_ = nullptr; -std::mutex subscribeSensorInfoMutex_; -SubscribeSensorInfo *subscribeSensorInfos_ = nullptr; +std::mutex sensorActiveInfoMutex_; +SensorActiveInfo *sensorActiveInfos_ = nullptr; int32_t sensorInfoCount_ = 0; std::map SensorAgentProxy::g_subscribeMap; std::map SensorAgentProxy::g_unsubscribeMap; @@ -269,9 +269,9 @@ int32_t SensorAgentProxy::SetMode(int32_t sensorId, const SensorUser *user, int3 void SensorAgentProxy::ClearSensorInfos() const { - if (subscribeSensorInfos_ != nullptr) { - free(subscribeSensorInfos_); - subscribeSensorInfos_ = nullptr; + if (sensorActiveInfos_ != nullptr) { + free(sensorActiveInfos_); + sensorActiveInfos_ = nullptr; } CHKPV(sensorInfos_); free(sensorInfos_); @@ -346,8 +346,8 @@ int32_t SensorAgentProxy::SuspendSensors(int32_t pid) const return PARAMETER_ERROR; } int32_t ret = SenClient.SuspendSensors(pid); - if (ret != 0) { - SEN_HILOGE("Suspend pid sensors failed, ret:%{public}d", ret); + if (ret != ERR_OK) { + SEN_HILOGE("Suspend sensors failed, ret:%{public}d", ret); } return ret; } @@ -360,75 +360,74 @@ int32_t SensorAgentProxy::ResumeSensors(int32_t pid) const return PARAMETER_ERROR; } int32_t ret = SenClient.ResumeSensors(pid); - if (ret != 0) { - SEN_HILOGE("Resume pid sensors failed, ret:%{public}d", ret); + if (ret != ERR_OK) { + SEN_HILOGE("Resume sensors failed, ret:%{public}d", ret); } return ret; } -int32_t SensorAgentProxy::GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **subscribeSensorInfos, int32_t *count) const +int32_t SensorAgentProxy::GetSensorActiveInfos(int32_t pid, SensorActiveInfo **sensorActiveInfos, int32_t *count) const { CALL_LOG_ENTER; if (pid < 0) { SEN_HILOGE("Pid is invalid"); return PARAMETER_ERROR; } - CHKPR(subscribeSensorInfos, OHOS::Sensors::ERROR); + CHKPR(sensorActiveInfos, OHOS::Sensors::ERROR); CHKPR(count, OHOS::Sensors::ERROR); - std::lock_guard subscribeSensorInfoLock(subscribeSensorInfoMutex_); - if (subscribeSensorInfos_ != nullptr) { - free(subscribeSensorInfos_); - subscribeSensorInfos_ = nullptr; + std::lock_guard sensorActiveInfoLock(sensorActiveInfoMutex_); + if (sensorActiveInfos_ != nullptr) { + free(sensorActiveInfos_); + sensorActiveInfos_ = nullptr; } - std::vector subscribeInfoList; - int32_t ret = SenClient.GetSubscribeInfoList(pid, subscribeInfoList); - if (ret != 0) { - SEN_HILOGE("Get subscribe info list failed, ret:%{public}d", ret); - return ERROR; + std::vector activeInfoList; + int32_t ret = SenClient.GetActiveInfoList(pid, activeInfoList); + if (ret != ERR_OK) { + SEN_HILOGE("Get active info list failed, ret:%{public}d", ret); + return ret; } - if (subscribeInfoList.empty()) { - SEN_HILOGE("Subscribe info list is empty"); + if (activeInfoList.empty()) { + SEN_HILOGE("Active info list is empty"); return ERROR; } - size_t subscribeInfoCount = subscribeInfoList.size(); - if (subscribeInfoCount > MAX_SENSOR_LIST_SIZE) { - SEN_HILOGE("The number of subscribe info exceeds the maximum value, count:%{public}zu", subscribeInfoCount); + size_t activeInfoCount = activeInfoList.size(); + if (activeInfoCount > MAX_SENSOR_LIST_SIZE) { + SEN_HILOGE("The number of active info exceeds the maximum value, count:%{public}zu", activeInfoCount); return ERROR; } - subscribeSensorInfos_ = (SubscribeSensorInfo *)malloc(sizeof(SubscribeSensorInfo) * subscribeInfoCount); - CHKPR(subscribeSensorInfos_, ERROR); - for (size_t i = 0; i < subscribeInfoCount; ++i) { - SubscribeSensorInfo *curSubscribeInfo= subscribeSensorInfos_ + i; - curSubscribeInfo->pid = subscribeInfoList[i].GetPid(); - curSubscribeInfo->sensorId = subscribeInfoList[i].GetSensorId(); - curSubscribeInfo->isActive = subscribeInfoList[i].IsActive(); - curSubscribeInfo->samplingPeriodNs = subscribeInfoList[i].GetSamplingPeriodNs(); - curSubscribeInfo->maxReportDelayNs = subscribeInfoList[i].GetMaxReportDelayNs(); - } - *subscribeSensorInfos = subscribeSensorInfos_; - *count = static_cast(subscribeInfoCount); - return SUCCESS; + sensorActiveInfos_ = (SensorActiveInfo *)malloc(sizeof(SensorActiveInfo) * activeInfoCount); + CHKPR(sensorActiveInfos_, ERROR); + for (size_t i = 0; i < activeInfoCount; ++i) { + SensorActiveInfo *curActiveInfo= sensorActiveInfos_ + i; + curActiveInfo->pid = activeInfoList[i].GetPid(); + curActiveInfo->sensorId = activeInfoList[i].GetSensorId(); + curActiveInfo->samplingPeriodNs = activeInfoList[i].GetSamplingPeriodNs(); + curActiveInfo->maxReportDelayNs = activeInfoList[i].GetMaxReportDelayNs(); + } + *sensorActiveInfos = sensorActiveInfos_; + *count = static_cast(activeInfoCount); + return ERR_OK; } -int32_t SensorAgentProxy::RegisterClientInfoCallback(ClientInfoCallback callback) const +int32_t SensorAgentProxy::RegisterSensorActiveInfoCB(SensorActiveInfoCB callback) const { CHKPR(callback, OHOS::Sensors::ERROR); CHKPR(dataChannel_, INVALID_POINTER); - int32_t ret = SenClient.RegisterClientInfoCallback(callback, dataChannel_); + int32_t ret = SenClient.RegisterSensorActiveInfoCB(callback, dataChannel_); if (ret != ERR_OK) { - SEN_HILOGE("Register client info callback failed, ret:%{public}d", ret); + SEN_HILOGE("Register sensor active info callback failed, ret:%{public}d", ret); } - return SUCCESS; + return ret; } -int32_t SensorAgentProxy::UnregisterClientInfoCallback(ClientInfoCallback callback) const +int32_t SensorAgentProxy::UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback) const { CHKPR(callback, OHOS::Sensors::ERROR); - int32_t ret = SenClient.UnregisterClientInfoCallback(callback); + int32_t ret = SenClient.UnregisterSensorActiveInfoCB(callback); if (ret != ERR_OK) { - SEN_HILOGE("Unregister client info callback failed, ret:%{public}d, ret", ret); + SEN_HILOGE("Unregister sensor active info callback failed, ret:%{public}d", ret); } - return SUCCESS; + return ret; } } // namespace Sensors } // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index 2979dfc6..df592125 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -265,7 +265,7 @@ int32_t SensorServiceClient::ResumeSensors(int32_t pid) FinishTrace(HITRACE_TAG_SENSORS); return ret; } -int32_t SensorServiceClient::GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) +int32_t SensorServiceClient::GetActiveInfoList(int32_t pid, std::vector &activeInfoList) { CALL_LOG_ENTER; int32_t ret = InitServiceClient(); @@ -274,36 +274,35 @@ int32_t SensorServiceClient::GetSubscribeInfoList(int32_t pid, std::vectorGetSubscribeInfoList(pid, subscribeInfoList); + StartTrace(HITRACE_TAG_SENSORS, "GetActiveInfoList"); + ret = sensorServer_->GetActiveInfoList(pid, activeInfoList); FinishTrace(HITRACE_TAG_SENSORS); return ret; } -int32_t SensorServiceClient::RegisterClientInfoCallback(ClientInfoCallback callback, sptr sensorDataChannel) +int32_t SensorServiceClient::RegisterSensorActiveInfoCB(SensorActiveInfoCB callback, sptr sensorDataChannel) { CALL_LOG_ENTER; - if (!isConnected_) { CHKPR(sensorDataChannel, INVALID_POINTER); dataChannel_ = sensorDataChannel; int32_t ret = CreateSocketChannel(); if (ret != ERR_OK) { - SEN_HILOGE("Register client info callback failed, ret:%{public}d", ret); + SEN_HILOGE("Register sensor active info callback failed, ret:%{public}d", ret); return ret; } } - std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); - clientInfoCallbackSet_.insert(callback); + std::lock_guard activeInfoCBLock(activeInfoCBMutex_); + activeInfoCBSet_.insert(callback); return ERR_OK; } -int32_t SensorServiceClient::UnregisterClientInfoCallback(ClientInfoCallback callback) +int32_t SensorServiceClient::UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback) { CALL_LOG_ENTER; - std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); - clientInfoCallbackSet_.erase(callback); - if (!clientInfoCallbackSet_.empty()) { + std::lock_guard activeInfoCBLock(activeInfoCBMutex_); + activeInfoCBSet_.erase(callback); + if (!activeInfoCBSet_.empty()) { return ERR_OK; } int32_t ret = InitServiceClient(); @@ -312,11 +311,11 @@ int32_t SensorServiceClient::UnregisterClientInfoCallback(ClientInfoCallback cal return ret; } CHKPR(sensorServer_, ERROR); - StartTrace(HITRACE_TAG_SENSORS, "DisableClientInfoCallback"); - ret = sensorServer_->DisableClientInfoCallback(); + StartTrace(HITRACE_TAG_SENSORS, "DisableActiveInfoCB"); + ret = sensorServer_->DisableActiveInfoCB(); FinishTrace(HITRACE_TAG_SENSORS); if (ret != ERR_OK) { - SEN_HILOGE("Disable clientInfo callback failed, ret:%{public}d", ret); + SEN_HILOGE("Disable active info callback failed, ret:%{public}d", ret); return ret; } Disconnect(); @@ -351,17 +350,17 @@ void SensorServiceClient::HandleNetPacke(NetPacket &pkt) SEN_HILOGE("NetPacke message id is not CLIENT_INFO"); return; } - SubscribeSensorInfo subscribeSensorInfo; - pkt >> subscribeSensorInfo.pid >> subscribeSensorInfo.sensorId >> subscribeSensorInfo.isActive >> - subscribeSensorInfo.samplingPeriodNs >> subscribeSensorInfo.maxReportDelayNs; + SensorActiveInfo sensorActiveInfo; + pkt >> sensorActiveInfo.pid >> sensorActiveInfo.sensorId >> sensorActiveInfo.samplingPeriodNs >> + sensorActiveInfo.maxReportDelayNs; if (pkt.ChkRWError()) { SEN_HILOGE("Packet read type failed"); return; } - std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); - for (auto callback : clientInfoCallbackSet_) { + std::lock_guard activeInfoCBLock(activeInfoCBMutex_); + for (auto callback : activeInfoCBSet_) { if (callback != nullptr) { - callback(subscribeSensorInfo); + callback(sensorActiveInfo); } } } @@ -406,11 +405,11 @@ int32_t SensorServiceClient::CreateSocketChannel() SEN_HILOGE("Add fd listener failed"); return ERROR; } - StartTrace(HITRACE_TAG_SENSORS, "EnableClientInfoCallback"); - ret = sensorServer_->EnableClientInfoCallback(); + StartTrace(HITRACE_TAG_SENSORS, "EnableActiveInfoCB"); + ret = sensorServer_->EnableActiveInfoCB(); FinishTrace(HITRACE_TAG_SENSORS); if (ret != ERR_OK) { - SEN_HILOGE("Enable clientInfo callback failed, ret:%{public}d", ret); + SEN_HILOGE("Enable active info callback failed, ret:%{public}d", ret); Disconnect(); return ret; } diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index e8834055..0dd3ac7c 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -239,7 +239,7 @@ ErrCode SensorServiceProxy::ResumeSensors(int32_t pid) return static_cast(ret); } -ErrCode SensorServiceProxy::GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) +ErrCode SensorServiceProxy::GetActiveInfoList(int32_t pid, std::vector &activeInfoList) { MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { @@ -254,26 +254,26 @@ ErrCode SensorServiceProxy::GetSubscribeInfoList(int32_t pid, std::vectorSendRequest(ISensorService::GET_SUBSCRIBE_INFO_LIST, data, reply, option); + int32_t ret = remote->SendRequest(ISensorService::GET_ACTIVE_INFO_LIST, data, reply, option); if (ret != NO_ERROR) { HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SENSOR_SERVICE_IPC_EXCEPTION", - HiSysEvent::EventType::FAULT, "PKG_NAME", "GetSubscribeInfoList", "ERROR_CODE", ret); + HiSysEvent::EventType::FAULT, "PKG_NAME", "GetActiveInfoList", "ERROR_CODE", ret); SEN_HILOGE("Failed, ret:%{public}d", ret); return static_cast(ret); } - int32_t subscribeInfoCount; - if (!reply.ReadInt32(subscribeInfoCount)) { - SEN_HILOGE("Parcel read subscribeInfoCount failed"); + int32_t activeInfoCount; + if (!reply.ReadInt32(activeInfoCount)) { + SEN_HILOGE("Parcel read activeInfoCount failed"); return READ_PARCEL_ERR; } - SubscribeInfo subscribeInfo; - for (int32_t i = 0; i < subscribeInfoCount; ++i) { - auto tmpSubscribeInfo = subscribeInfo.Unmarshalling(reply); - if (tmpSubscribeInfo == nullptr) { - SEN_HILOGE("Current subscribeInfo is nullptr, i:%{public}d", i); + ActiveInfo activeInfo; + for (int32_t i = 0; i < activeInfoCount; ++i) { + auto tmpActiveInfo = activeInfo.Unmarshalling(reply); + if (tmpActiveInfo == nullptr) { + SEN_HILOGE("Current activeInfo is nullptr, i:%{public}d", i); continue; } - subscribeInfoList.push_back(*tmpSubscribeInfo); + activeInfoList.push_back(*tmpActiveInfo); } return static_cast(ret); } @@ -334,7 +334,7 @@ ErrCode SensorServiceProxy::DestroySocketChannel(const sptr &sens return static_cast(ret); } -ErrCode SensorServiceProxy::EnableClientInfoCallback() +ErrCode SensorServiceProxy::EnableActiveInfoCB() { MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { @@ -345,16 +345,16 @@ ErrCode SensorServiceProxy::EnableClientInfoCallback() CHKPR(remote, ERROR); MessageParcel reply; MessageOption option; - int32_t ret = remote->SendRequest(ISensorService::ENABLE_CLIENT_INFO_CALLBACK, data, reply, option); + int32_t ret = remote->SendRequest(ISensorService::ENABLE_ACTIVE_INFO_CB, data, reply, option); if (ret != NO_ERROR) { HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SERVICE_IPC_EXCEPTION", - HiSysEvent::EventType::FAULT, "PKG_NAME", "EnableClientInfoCallback", "ERROR_CODE", ret); + HiSysEvent::EventType::FAULT, "PKG_NAME", "EnableActiveInfoCB", "ERROR_CODE", ret); SEN_HILOGE("failed, ret:%{public}d", ret); } return static_cast(ret); } -ErrCode SensorServiceProxy::DisableClientInfoCallback() +ErrCode SensorServiceProxy::DisableActiveInfoCB() { MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { @@ -365,10 +365,10 @@ ErrCode SensorServiceProxy::DisableClientInfoCallback() CHKPR(remote, ERROR); MessageParcel reply; MessageOption option; - int32_t ret = remote->SendRequest(ISensorService::DISABLE_CLIENT_INFO_CALLBACK, data, reply, option); + int32_t ret = remote->SendRequest(ISensorService::DISABLE_ACTIVE_INFO_CB, data, reply, option); if (ret != NO_ERROR) { HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SERVICE_IPC_EXCEPTION", - HiSysEvent::EventType::FAULT, "PKG_NAME", "DISABLE_CLIENT_INFO_CALLBACK", "ERROR_CODE", ret); + HiSysEvent::EventType::FAULT, "PKG_NAME", "DisableActiveInfoCB", "ERROR_CODE", ret); SEN_HILOGE("failed, ret:%{public}d", ret); } return static_cast(ret); diff --git a/interfaces/native/include/sensor_agent.h b/interfaces/native/include/sensor_agent.h index afc4331f..50b37f8c 100755 --- a/interfaces/native/include/sensor_agent.h +++ b/interfaces/native/include/sensor_agent.h @@ -146,34 +146,34 @@ int32_t SuspendSensors(int32_t pid); */ int32_t ResumeSensors(int32_t pid); /** - * @brief 查询一个进程订阅的所有传感器的信息 + * @brief 查询一个进程打开的所有传感器的信息 * * @param pid 进程号 - * @param subscribeSensorInfos 返回进程订阅的所有传感器信息 - * @param count 返回进程订阅的传感器数量 + * @param sensorActiveInfos 返回进程打开的所有传感器信息 + * @param count 返回进程打开的传感器数量 * @return 返回0表示成功,否则表示失败 * * @since 10 */ -int32_t GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **subscribeSensorInfos, int32_t *count); +int32_t GetSensorActiveInfos(int32_t pid, SensorActiveInfo **sensorActiveInfos, int32_t *count); /** - * @brief 注册传感器订阅信息上报函数 + * @brief 注册传感器打开信息上报函数 * * @param callback 回调函数 * @return 返回0表示成功,否则表示失败 * * @since 10 */ -int32_t RegisterClientInfoCallback(ClientInfoCallback callback); +int32_t RegisterSensorActiveInfoCB(SensorActiveInfoCB callback); /** - * @brief 取消注册传感器订阅信息上报函数 + * @brief 取消注册传感器打开信息上报函数 * * @param callback 回调函数 * @return 返回0表示成功,否则表示失败 * * @since 10 */ -int32_t UnregisterClientInfoCallback(ClientInfoCallback callback); +int32_t UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback); #ifdef __cplusplus #if __cplusplus diff --git a/interfaces/native/include/sensor_agent_type.h b/interfaces/native/include/sensor_agent_type.h index 9448f98c..46d94880 100644 --- a/interfaces/native/include/sensor_agent_type.h +++ b/interfaces/native/include/sensor_agent_type.h @@ -395,15 +395,14 @@ typedef struct WearDetectionData { float value; } WearDetectionData; -typedef struct SubscribeSensorInfo { +typedef struct SensorActiveInfo { int32_t pid = -1; /**< PID */ int32_t sensorId = -1; /**< Sensor ID */ - bool isActive = false; /**< Whether the process enable the sensor */ int64_t samplingPeriodNs = -1; /**< Sample period, in ns */ int64_t maxReportDelayNs = -1; /**< Maximum Report Delay, in ns */ -} SubscribeSensorInfo; +} SensorActiveInfo; -typedef void (*ClientInfoCallback)(SubscribeSensorInfo &subscribeSensorInfo); +typedef void (*SensorActiveInfoCB)(SensorActiveInfo &sensorActiveInfo); #ifdef __cplusplus #if __cplusplus diff --git a/interfaces/native/src/sensor_agent.cpp b/interfaces/native/src/sensor_agent.cpp index 9c400650..64b055a5 100755 --- a/interfaces/native/src/sensor_agent.cpp +++ b/interfaces/native/src/sensor_agent.cpp @@ -157,7 +157,7 @@ int32_t SuspendSensors(int32_t pid) } int32_t ret = proxy->SuspendSensors(pid); if (ret != OHOS::ERR_OK) { - SEN_HILOGE("Suspend pid sensors failed, ret:%{public}d", ret); + SEN_HILOGE("Suspend sensors failed, ret:%{public}d", ret); return NormalizeErrCode(ret); } return ret; @@ -172,54 +172,54 @@ int32_t ResumeSensors(int32_t pid) } int32_t ret = proxy->ResumeSensors(pid); if (ret != OHOS::ERR_OK) { - SEN_HILOGE("Resume pid sensors failed, ret:%{public}d", ret); + SEN_HILOGE("Resume sensors failed, ret:%{public}d", ret); return NormalizeErrCode(ret); } return ret; } -int32_t GetSubscribeInfos(int32_t pid, SubscribeSensorInfo **subscribeSensorInfos, int32_t *count) +int32_t GetSensorActiveInfos(int32_t pid, SensorActiveInfo **sensorActiveInfos, int32_t *count) { - CHKPR(subscribeSensorInfos, OHOS::Sensors::ERROR); + CHKPR(sensorActiveInfos, OHOS::Sensors::ERROR); CHKPR(count, OHOS::Sensors::ERROR); const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("Proxy is nullptr"); return SERVICE_EXCEPTION; } - int32_t ret = proxy->GetSubscribeInfos(pid, subscribeSensorInfos, count); + int32_t ret = proxy->GetSensorActiveInfos(pid, sensorActiveInfos, count); if (ret != OHOS::ERR_OK) { - SEN_HILOGE("Get subscribe Infos failed, ret:%{public}d", ret); + SEN_HILOGE("Get sensor active infos failed, ret:%{public}d", ret); return NormalizeErrCode(ret); } return ret; } -int32_t RegisterClientInfoCallback(ClientInfoCallback callback) +int32_t RegisterSensorActiveInfoCB(SensorActiveInfoCB callback) { const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); return SERVICE_EXCEPTION; } - int32_t ret = proxy->RegisterClientInfoCallback(callback); + int32_t ret = proxy->RegisterSensorActiveInfoCB(callback); if (ret != OHOS::ERR_OK) { - SEN_HILOGE("Register client info callback failed, ret:%{public}d", ret); + SEN_HILOGE("Register sensor active Info callback failed, ret:%{public}d", ret); return NormalizeErrCode(ret); } return ret; } -int32_t UnregisterClientInfoCallback(ClientInfoCallback callback) +int32_t UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback) { const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); return SERVICE_EXCEPTION; } - int32_t ret = proxy->UnregisterClientInfoCallback(callback); + int32_t ret = proxy->UnregisterSensorActiveInfoCB(callback); if (ret != OHOS::ERR_OK) { - SEN_HILOGE("Unregister client info callback failed, ret:%{public}d", ret); + SEN_HILOGE("Unregister sensor active info callback failed, ret:%{public}d", ret); return NormalizeErrCode(ret); } return ret; diff --git a/services/sensor/include/client_info.h b/services/sensor/include/client_info.h index dd4167be..f35164db 100644 --- a/services/sensor/include/client_info.h +++ b/services/sensor/include/client_info.h @@ -76,9 +76,9 @@ public: int32_t GetUidByPid(int32_t pid); AccessTokenID GetTokenIdByPid(int32_t pid); - int32_t AddClientInfoCallbackPid(int32_t pid); - int32_t DelClientInfoCallbackPid(int32_t pid); - std::unordered_set GetClientInfoCallbackPidSet(); + int32_t AddActiveInfoCBPid(int32_t pid); + int32_t DelActiveInfoCBPid(int32_t pid); + std::unordered_set GetActiveInfoCBPid(); bool IsUnregisterClientDeathRecipient(int32_t pid); private: @@ -99,8 +99,8 @@ private: std::unordered_map>> cmdMap_; std::unordered_map> dumpQueue_; - std::mutex clientInfoCallbackMutex_; - std::unordered_set clientInfoCallbackPidSet_; + std::mutex activeInfoCBPidMutex_; + std::unordered_set activeInfoCBPidSet_; }; } // namespace Sensors } // namespace OHOS diff --git a/services/sensor/include/sensor_service.h b/services/sensor/include/sensor_service.h index ccd7a65b..ab5073b9 100644 --- a/services/sensor/include/sensor_service.h +++ b/services/sensor/include/sensor_service.h @@ -58,11 +58,11 @@ public: void ProcessDeathObserver(const wptr &object); ErrCode SuspendSensors(int32_t pid) override; ErrCode ResumeSensors(int32_t pid) override; - ErrCode GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) override; + ErrCode GetActiveInfoList(int32_t pid, std::vector &activeInfoList) override; ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) override; ErrCode DestroySocketChannel(const sptr &sensorClient) override; - ErrCode EnableClientInfoCallback() override; - ErrCode DisableClientInfoCallback() override; + ErrCode EnableActiveInfoCB() override; + ErrCode DisableActiveInfoCB() override; private: DISALLOW_COPY_AND_MOVE(SensorService); @@ -93,8 +93,8 @@ private: sptr clientDeathObserver_ = nullptr; ErrCode SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); - std::atomic_bool isReportClientInfo_ = false; - void ReportClientInfo(int32_t sensorId, bool isActive, int32_t pid); + std::atomic_bool isReportActiveInfo_ = false; + void ReportActiveInfo(int32_t sensorId, int32_t pid); }; } // namespace Sensors } // namespace OHOS diff --git a/services/sensor/include/sensor_service_stub.h b/services/sensor/include/sensor_service_stub.h index 6e79f402..60b4ba49 100644 --- a/services/sensor/include/sensor_service_stub.h +++ b/services/sensor/include/sensor_service_stub.h @@ -41,11 +41,11 @@ private: ErrCode DestroyDataChannelInner(MessageParcel &data, MessageParcel &reply); ErrCode SuspendSensorsInner(MessageParcel &data, MessageParcel &reply); ErrCode ResumeSensorsInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetSubscribeInfoListInner(MessageParcel &data, MessageParcel &reply); + ErrCode GetActiveInfoListInner(MessageParcel &data, MessageParcel &reply); ErrCode CreateSocketChannelInner(MessageParcel &data, MessageParcel &reply); ErrCode DestroySocketChannelInner(MessageParcel &data, MessageParcel &reply); - ErrCode EnableClientInfoCallbackInner(MessageParcel &data, MessageParcel &reply); - ErrCode DisableClientInfoCallbackInner(MessageParcel &data, MessageParcel &reply); + ErrCode EnableActiveInfoCBInner(MessageParcel &data, MessageParcel &reply); + ErrCode DisableActiveInfoCBInner(MessageParcel &data, MessageParcel &reply); std::unordered_map baseFuncs_; }; } // namespace Sensors diff --git a/services/sensor/include/sensor_suspend_policy.h b/services/sensor/include/sensor_suspend_policy.h index 35769bc8..a270beb1 100644 --- a/services/sensor/include/sensor_suspend_policy.h +++ b/services/sensor/include/sensor_suspend_policy.h @@ -28,16 +28,16 @@ #include "sensor_manager.h" #include "sensors_errors.h" #include "stream_session.h" -#include "subscribe_info.h" +#include "active_info.h" namespace OHOS { namespace Sensors { class SensorSuspendPolicy : public Singleton{ public: - ErrCode DoSuspend(int32_t pid); - ErrCode DoResume(int32_t pid); - ErrCode GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList); - void ReportClientInfo(SubscribeSensorInfo subscribeSensorInfo, const std::vector &sessionList); + ErrCode SuspendSensors(int32_t pid); + ErrCode ResumeSensors(int32_t pid); + ErrCode GetActiveInfoList(int32_t pid, std::vector &activeInfoList); + void ReportActiveInfo(ActiveInfo activeInfo, const std::vector &sessionList); private: bool CheckFreezingSensor(int32_t sensorId); diff --git a/services/sensor/src/client_info.cpp b/services/sensor/src/client_info.cpp index 18037d30..c53cb768 100644 --- a/services/sensor/src/client_info.cpp +++ b/services/sensor/src/client_info.cpp @@ -685,32 +685,32 @@ void ClientInfo::ClearDataQueue(int32_t sensorId) } } -int32_t ClientInfo::AddClientInfoCallbackPid(int32_t pid) +int32_t ClientInfo::AddActiveInfoCBPid(int32_t pid) { - std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); - auto pairRet = clientInfoCallbackPidSet_.insert(pid); + std::lock_guard activeInfoCBPidLock(activeInfoCBPidMutex_); + auto pairRet = activeInfoCBPidSet_.insert(pid); if (!pairRet.second) { - SEN_HILOGE("ClientInfoCallbackPidSet_ insert pid fail"); + SEN_HILOGE("ActiveInfoCBPidSet insert pid fail"); return ERROR; } return ERR_OK; } -int32_t ClientInfo::DelClientInfoCallbackPid(int32_t pid) +int32_t ClientInfo::DelActiveInfoCBPid(int32_t pid) { - std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); - auto it = clientInfoCallbackPidSet_.find(pid); - if (it == clientInfoCallbackPidSet_.end()) { - SEN_HILOGE("ClientInfoCallbackPidSet_ not find pid"); + std::lock_guard activeInfoCBPidLock(activeInfoCBPidMutex_); + auto it = activeInfoCBPidSet_.find(pid); + if (it == activeInfoCBPidSet_.end()) { + SEN_HILOGE("ActiveInfoCBPidSet not find pid"); return ERROR; } - clientInfoCallbackPidSet_.erase(it); + activeInfoCBPidSet_.erase(it); return ERR_OK; } -std::unordered_set ClientInfo::GetClientInfoCallbackPidSet() +std::unordered_set ClientInfo::GetActiveInfoCBPid() { - return clientInfoCallbackPidSet_; + return activeInfoCBPidSet_; } bool ClientInfo::IsUnregisterClientDeathRecipient(int32_t pid) @@ -721,10 +721,10 @@ bool ClientInfo::IsUnregisterClientDeathRecipient(int32_t pid) SEN_HILOGD("pid exist in channelMap"); return false; } - std::lock_guard clientInfoCallbackLock(clientInfoCallbackMutex_); - auto pidIt = clientInfoCallbackPidSet_.find(pid); - if (pidIt != clientInfoCallbackPidSet_.end()) { - SEN_HILOGD("pid exist in clientInfoCallbackPidSet"); + std::lock_guard activeInfoCBPidLock(activeInfoCBPidMutex_); + auto pidIt = activeInfoCBPidSet_.find(pid); + if (pidIt != activeInfoCBPidSet_.end()) { + SEN_HILOGD("pid exist in activeInfoCBPidSet"); return false; } return true; diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index e98885d1..4ce764f9 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -235,8 +235,8 @@ ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, SEN_HILOGE("ret : %{public}d", ret); } ReportOnChangeData(sensorId); - if (isReportClientInfo_) { - ReportClientInfo(sensorId, true, pid); + if (isReportActiveInfo_) { + ReportActiveInfo(sensorId, pid); } return ERR_OK; } @@ -253,8 +253,8 @@ ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, return ENABLE_SENSOR_ERR; } ReportSensorSysEvent(sensorId, true, pid); - if (isReportClientInfo_) { - ReportClientInfo(sensorId, true, pid); + if (isReportActiveInfo_) { + ReportActiveInfo(sensorId, pid); } return ret; } @@ -274,9 +274,6 @@ ErrCode SensorService::DisableSensor(int32_t sensorId, int32_t pid) std::lock_guard serviceLock(serviceLock_); if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { SEN_HILOGW("other client is using this sensor now, cannot disable"); - if (isReportClientInfo_) { - ReportClientInfo(sensorId, false, pid); - } return ERR_OK; } if (sensorHdiConnection_.DisableSensor(sensorId) != ERR_OK) { @@ -286,9 +283,6 @@ ErrCode SensorService::DisableSensor(int32_t sensorId, int32_t pid) int32_t uid = clientInfo_.GetUidByPid(pid); clientInfo_.DestroyCmd(uid); clientInfo_.ClearDataQueue(sensorId); - if (isReportClientInfo_) { - ReportClientInfo(sensorId, false, pid); - } return sensorManager_.AfterDisableSensor(sensorId); } @@ -437,12 +431,7 @@ ErrCode SensorService::SuspendSensors(int32_t pid) SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } - int32_t ret = suspendPolicy_.DoSuspend(pid); - if (ret != ERR_OK) { - SEN_HILOGE("Suspend pid sensors failed, ret:%{public}d", ret); - return ERROR; - } - return ERR_OK; + return suspendPolicy_.SuspendSensors(pid); } ErrCode SensorService::ResumeSensors(int32_t pid) @@ -452,27 +441,17 @@ ErrCode SensorService::ResumeSensors(int32_t pid) SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } - int32_t ret = suspendPolicy_.DoResume(pid); - if (ret != ERR_OK) { - SEN_HILOGE("Resume pid sensors failed, ret:%{public}d", ret); - return ERROR; - } - return ERR_OK; + return suspendPolicy_.ResumeSensors(pid); } -ErrCode SensorService::GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) +ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector &activeInfoList) { CALL_LOG_ENTER; if (pid < 0) { SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } - int32_t ret = suspendPolicy_.GetSubscribeInfoList(pid, subscribeInfoList); - if (ret != ERR_OK) { - SEN_HILOGE("Get subscribe info list failed, ret:%{public}d", ret); - return ERROR; - } - return ERR_OK; + return suspendPolicy_.GetActiveInfoList(pid, activeInfoList); } ErrCode SensorService::CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) @@ -486,7 +465,7 @@ ErrCode SensorService::CreateSocketChannel(int32_t &clientFd, const sptr &sensorCli return ERR_OK; } -ErrCode SensorService::EnableClientInfoCallback() +ErrCode SensorService::EnableActiveInfoCB() { CALL_LOG_ENTER; - isReportClientInfo_ = true; + isReportActiveInfo_ = true; int32_t pid = GetCallingPid(); - return clientInfo_.AddClientInfoCallbackPid(pid); + return clientInfo_.AddActiveInfoCBPid(pid); } -ErrCode SensorService::DisableClientInfoCallback() +ErrCode SensorService::DisableActiveInfoCB() { CALL_LOG_ENTER; - isReportClientInfo_ = false; + isReportActiveInfo_ = false; int32_t pid = GetCallingPid(); - return clientInfo_.DelClientInfoCallbackPid(pid); + return clientInfo_.DelActiveInfoCBPid(pid); } -void SensorService::ReportClientInfo(int32_t sensorId, bool isActive, int32_t pid) +void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid) { CALL_LOG_ENTER; std::vector sessionList; - auto pidSet = clientInfo_.GetClientInfoCallbackPidSet(); + auto pidSet = clientInfo_.GetActiveInfoCBPid(); for (auto pid : pidSet) { auto sess = GetSessionByPid(pid); if (sess != nullptr) { @@ -529,13 +508,9 @@ void SensorService::ReportClientInfo(int32_t sensorId, bool isActive, int32_t pi } } SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); - SubscribeSensorInfo subscribeSensorInfo; - subscribeSensorInfo.pid = pid; - subscribeSensorInfo.sensorId = sensorId; - subscribeSensorInfo.isActive = isActive; - subscribeSensorInfo.samplingPeriodNs = sensorInfo.GetSamplingPeriodNs(); - subscribeSensorInfo.maxReportDelayNs = sensorInfo.GetMaxReportDelayNs(); - suspendPolicy_.ReportClientInfo(subscribeSensorInfo, sessionList); + ActiveInfo activeInfo(pid, sensorId, sensorInfo.GetSamplingPeriodNs(), + sensorInfo.GetMaxReportDelayNs()); + suspendPolicy_.ReportActiveInfo(activeInfo, sessionList); } } // namespace Sensors } // namespace OHOS diff --git a/services/sensor/src/sensor_service_stub.cpp b/services/sensor/src/sensor_service_stub.cpp index 744ed910..f9d88729 100755 --- a/services/sensor/src/sensor_service_stub.cpp +++ b/services/sensor/src/sensor_service_stub.cpp @@ -44,11 +44,11 @@ SensorServiceStub::SensorServiceStub() baseFuncs_[DESTROY_SENSOR_CHANNEL] = &SensorServiceStub::DestroyDataChannelInner; baseFuncs_[SUSPEND_SENSORS] = &SensorServiceStub::SuspendSensorsInner; baseFuncs_[RESUME_SENSORS] = &SensorServiceStub::ResumeSensorsInner; - baseFuncs_[GET_SUBSCRIBE_INFO_LIST] = &SensorServiceStub::GetSubscribeInfoListInner; + baseFuncs_[GET_ACTIVE_INFO_LIST] = &SensorServiceStub::GetActiveInfoListInner; baseFuncs_[CREATE_SOCKET_CHANNEL] = &SensorServiceStub::CreateSocketChannelInner; baseFuncs_[DESTROY_SOCKET_CHANNEL] = &SensorServiceStub::DestroySocketChannelInner; - baseFuncs_[ENABLE_CLIENT_INFO_CALLBACK] = &SensorServiceStub::EnableClientInfoCallbackInner; - baseFuncs_[DISABLE_CLIENT_INFO_CALLBACK] = &SensorServiceStub::DisableClientInfoCallbackInner; + baseFuncs_[ENABLE_ACTIVE_INFO_CB] = &SensorServiceStub::EnableActiveInfoCBInner; + baseFuncs_[DISABLE_ACTIVE_INFO_CB] = &SensorServiceStub::DisableActiveInfoCBInner; } SensorServiceStub::~SensorServiceStub() @@ -192,7 +192,7 @@ ErrCode SensorServiceStub::ResumeSensorsInner(MessageParcel &data, MessageParcel return ResumeSensors(pid); } -ErrCode SensorServiceStub::GetSubscribeInfoListInner(MessageParcel &data, MessageParcel &reply) +ErrCode SensorServiceStub::GetActiveInfoListInner(MessageParcel &data, MessageParcel &reply) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { @@ -204,17 +204,17 @@ ErrCode SensorServiceStub::GetSubscribeInfoListInner(MessageParcel &data, Messag SEN_HILOGE("Parcel read failed"); return ERROR; } - std::vector subscribeInfoList; - GetSubscribeInfoList(pid, subscribeInfoList); - int32_t subscribeInfoCount = int32_t { subscribeInfoList.size() }; - reply.WriteInt32(subscribeInfoCount); - for (int32_t i = 0; i < subscribeInfoCount; i++) { - if (!subscribeInfoList[i].Marshalling(reply)) { - SEN_HILOGE("SubscribeInfo %{public}d failed", i); + std::vector activeInfoList; + GetActiveInfoList(pid, activeInfoList); + int32_t activeInfoCount = int32_t { activeInfoList.size() }; + reply.WriteInt32(activeInfoCount); + for (int32_t i = 0; i < activeInfoCount; i++) { + if (!activeInfoList[i].Marshalling(reply)) { + SEN_HILOGE("ActiveInfo %{public}d failed", i); return ERROR; } } - return NO_ERROR; + return ERR_OK; } ErrCode SensorServiceStub::CreateSocketChannelInner(MessageParcel &data, MessageParcel &reply) @@ -251,24 +251,24 @@ ErrCode SensorServiceStub::DestroySocketChannelInner(MessageParcel &data, Messag return ERR_OK; } -ErrCode SensorServiceStub::EnableClientInfoCallbackInner(MessageParcel &data, MessageParcel &reply) +ErrCode SensorServiceStub::EnableActiveInfoCBInner(MessageParcel &data, MessageParcel &reply) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { SEN_HILOGE("TokenType is not TOKEN_NATIVE"); return PERMISSION_DENIED; } - return EnableClientInfoCallback(); + return EnableActiveInfoCB(); } -ErrCode SensorServiceStub::DisableClientInfoCallbackInner(MessageParcel &data, MessageParcel &reply) +ErrCode SensorServiceStub::DisableActiveInfoCBInner(MessageParcel &data, MessageParcel &reply) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { SEN_HILOGE("TokenType is not TOKEN_NATIVE"); return PERMISSION_DENIED; } - return DisableClientInfoCallback(); + return DisableActiveInfoCB(); } } // namespace Sensors } // namespace OHOS diff --git a/services/sensor/src/sensor_suspend_policy.cpp b/services/sensor/src/sensor_suspend_policy.cpp index a86c25ad..02edb18c 100644 --- a/services/sensor/src/sensor_suspend_policy.cpp +++ b/services/sensor/src/sensor_suspend_policy.cpp @@ -33,7 +33,7 @@ bool SensorSuspendPolicy::CheckFreezingSensor(int32_t sensorId) return ((sensorId == SENSOR_TYPE_ID_PEDOMETER_DETECTION) || (sensorId == SENSOR_TYPE_ID_PEDOMETER)); } -ErrCode SensorSuspendPolicy::DoSuspend(int32_t pid) +ErrCode SensorSuspendPolicy::SuspendSensors(int32_t pid) { CALL_LOG_ENTER; std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); @@ -107,7 +107,7 @@ ErrCode SensorSuspendPolicy::DisableSensor(std::unordered_map pidSensorInfoLock(pidSensorInfoMutex_); @@ -188,46 +188,26 @@ ErrCode SensorSuspendPolicy::RestoreSensorInfo(int32_t sensorId, int32_t pid, in return ret; } -ErrCode SensorSuspendPolicy::GetSubscribeInfoList(int32_t pid, std::vector &subscribeInfoList) +ErrCode SensorSuspendPolicy::GetActiveInfoList(int32_t pid, std::vector &activeInfoList) { CALL_LOG_ENTER; std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); for (auto &sensorId : sensorIdList) { auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); - SubscribeSensorInfo subscribeSensorInfo; - subscribeSensorInfo.pid = pid; - subscribeSensorInfo.sensorId = sensorId; - subscribeSensorInfo.isActive = true; - subscribeSensorInfo.samplingPeriodNs = sensorInfo.GetSamplingPeriodNs(); - subscribeSensorInfo.maxReportDelayNs = sensorInfo.GetMaxReportDelayNs(); - SubscribeInfo subscribeInfo(subscribeSensorInfo); - subscribeInfoList.push_back(subscribeInfo); - } - std::lock_guard pidSensorInfoLock(pidSensorInfoMutex_); - auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); - if (pidSensorInfoIt != pidSensorInfoMap_.end()) { - std::unordered_map SensorInfoMap = pidSensorInfoIt->second; - for (auto &sensorInfo : SensorInfoMap) { - SubscribeSensorInfo subscribeSensorInfo; - subscribeSensorInfo.pid = pid; - subscribeSensorInfo.sensorId = sensorInfo.first; - subscribeSensorInfo.isActive = false; - subscribeSensorInfo.samplingPeriodNs = sensorInfo.second.GetSamplingPeriodNs(); - subscribeSensorInfo.maxReportDelayNs = sensorInfo.second.GetMaxReportDelayNs(); - SubscribeInfo subscribeInfo(subscribeSensorInfo); - subscribeInfoList.push_back(subscribeInfo); - } + ActiveInfo activeInfo(pid, sensorId, sensorInfo.GetSamplingPeriodNs(), + sensorInfo.GetMaxReportDelayNs()); + activeInfoList.push_back(activeInfo); } return ERR_OK; } -void SensorSuspendPolicy::ReportClientInfo(SubscribeSensorInfo subscribeSensorInfo, +void SensorSuspendPolicy::ReportActiveInfo(ActiveInfo activeInfo, const std::vector &sessionList) { CALL_LOG_ENTER; NetPacket pkt(MessageId::CLIENT_INFO); - pkt << subscribeSensorInfo.pid << subscribeSensorInfo.sensorId << subscribeSensorInfo.isActive << - subscribeSensorInfo.samplingPeriodNs << subscribeSensorInfo.maxReportDelayNs; + pkt << activeInfo.GetPid() << activeInfo.GetSensorId() << + activeInfo.GetSamplingPeriodNs() << activeInfo.GetMaxReportDelayNs(); if (pkt.ChkRWError()) { SEN_HILOGE("Packet write data failed"); return; diff --git a/utils/common/BUILD.gn b/utils/common/BUILD.gn index 5e1ef88f..64b32943 100644 --- a/utils/common/BUILD.gn +++ b/utils/common/BUILD.gn @@ -21,7 +21,7 @@ ohos_shared_library("libsensor_utils") { "src/sensor_basic_data_channel.cpp", "src/sensor_basic_info.cpp", "src/sensor_channel_info.cpp", - "src/subscribe_info.cpp", + "src/active_info.cpp", ] include_dirs = [ diff --git a/utils/common/include/subscribe_info.h b/utils/common/include/active_info.h similarity index 73% rename from utils/common/include/subscribe_info.h rename to utils/common/include/active_info.h index fbcd41b1..f068912a 100644 --- a/utils/common/include/subscribe_info.h +++ b/utils/common/include/active_info.h @@ -13,40 +13,35 @@ * limitations under the License. */ -#ifndef SUBSCRIBE_INFO_H -#define SUBSCRIBE_INFO_H +#ifndef ACTIVE_INFO_H +#define ACTIVE_INFO_H #include "parcel.h" -#include "sensor_agent_type.h" - namespace OHOS { namespace Sensors { -class SubscribeInfo : public Parcelable { +class ActiveInfo : public Parcelable { public: - SubscribeInfo() = default; - SubscribeInfo(SubscribeSensorInfo subscribeSensorInfo); - virtual ~SubscribeInfo() = default; + ActiveInfo() = default; + ActiveInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + virtual ~ActiveInfo() = default; int32_t GetPid() const; void SetPid(int32_t pid); int32_t GetSensorId() const; void SetSensorId(int32_t sensorId); - bool IsActive() const; - void Enable(bool isActive); int64_t GetSamplingPeriodNs() const; void SetSamplingPeriodNs(int64_t samplingPeriodNs); int64_t GetMaxReportDelayNs() const; void SetMaxReportDelayNs(int64_t maxReportDelayNs); bool Marshalling(Parcel &parcel) const; - std::unique_ptr Unmarshalling(Parcel &parcel); + std::unique_ptr Unmarshalling(Parcel &parcel); private: int32_t pid_ { -1 }; int32_t sensorId_ { -1 }; - bool isActive_ { -1 }; int64_t samplingPeriodNs_ { -1 }; int64_t maxReportDelayNs_ { -1 }; }; } // namespace Sensors } // namespace OHOS -#endif // SUBSCRIBE_INFO_H \ No newline at end of file +#endif // ACTIVE_INFO_H \ No newline at end of file diff --git a/utils/common/src/subscribe_info.cpp b/utils/common/src/active_info.cpp similarity index 52% rename from utils/common/src/subscribe_info.cpp rename to utils/common/src/active_info.cpp index 18c8605c..270b479d 100644 --- a/utils/common/src/subscribe_info.cpp +++ b/utils/common/src/active_info.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "subscribe_info.h" +#include "active_info.h" #include "sensors_errors.h" @@ -21,69 +21,53 @@ namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; namespace { -constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SubscribeInfo" }; +constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "ActiveInfo" }; } -SubscribeInfo::SubscribeInfo(SubscribeSensorInfo subscribeSensorInfo) -{ - pid_ = subscribeSensorInfo.pid; - sensorId_ = subscribeSensorInfo.sensorId; - isActive_ = subscribeSensorInfo.isActive; - samplingPeriodNs_ = subscribeSensorInfo.samplingPeriodNs; - maxReportDelayNs_ = subscribeSensorInfo.maxReportDelayNs; -} +ActiveInfo::ActiveInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) + :pid_(pid), sensorId_(sensorId), samplingPeriodNs_(samplingPeriodNs), maxReportDelayNs_(maxReportDelayNs) {}; -int32_t SubscribeInfo::GetPid() const +int32_t ActiveInfo::GetPid() const { return pid_; } -void SubscribeInfo::SetPid(int32_t pid) +void ActiveInfo::SetPid(int32_t pid) { pid_ = pid; } -int32_t SubscribeInfo::GetSensorId() const +int32_t ActiveInfo::GetSensorId() const { return sensorId_; } -void SubscribeInfo::SetSensorId(int32_t sensorId) +void ActiveInfo::SetSensorId(int32_t sensorId) { sensorId_ = sensorId; } -bool SubscribeInfo::IsActive() const -{ - return isActive_; -} - -void SubscribeInfo::Enable(bool isActive) -{ - isActive_ = isActive; -} - -int64_t SubscribeInfo::GetSamplingPeriodNs() const +int64_t ActiveInfo::GetSamplingPeriodNs() const { return samplingPeriodNs_; } -void SubscribeInfo::SetSamplingPeriodNs(int64_t samplingPeriodNs) +void ActiveInfo::SetSamplingPeriodNs(int64_t samplingPeriodNs) { samplingPeriodNs_ = samplingPeriodNs; } -int64_t SubscribeInfo::GetMaxReportDelayNs() const +int64_t ActiveInfo::GetMaxReportDelayNs() const { return maxReportDelayNs_; } -void SubscribeInfo::SetMaxReportDelayNs(int64_t maxReportDelayNs) +void ActiveInfo::SetMaxReportDelayNs(int64_t maxReportDelayNs) { maxReportDelayNs_ = maxReportDelayNs; } -bool SubscribeInfo::Marshalling(Parcel &parcel) const +bool ActiveInfo::Marshalling(Parcel &parcel) const { if (!parcel.WriteInt32(pid_)) { SEN_HILOGE("Write pid failed"); @@ -93,10 +77,6 @@ bool SubscribeInfo::Marshalling(Parcel &parcel) const SEN_HILOGE("Write sensorId failed"); return false; } - if (!parcel.WriteBool(isActive_)) { - SEN_HILOGE("Write isActive failed"); - return false; - } if (!parcel.WriteInt64(samplingPeriodNs_)) { SEN_HILOGE("Write samplingPeriodNs failed"); return false; @@ -108,25 +88,23 @@ bool SubscribeInfo::Marshalling(Parcel &parcel) const return true; } -std::unique_ptr SubscribeInfo::Unmarshalling(Parcel &parcel) +std::unique_ptr ActiveInfo::Unmarshalling(Parcel &parcel) { int32_t pid = -1; int32_t sensorId = -1; - bool isActive = false; int64_t samplingPeriodNs = -1; int64_t maxReportDelayNs = -1; - if (!(parcel.ReadInt32(pid) && parcel.ReadInt32(sensorId) && parcel.ReadBool(isActive) && + if (!(parcel.ReadInt32(pid) && parcel.ReadInt32(sensorId) && parcel.ReadInt64(samplingPeriodNs) && parcel.ReadInt64(maxReportDelayNs))) { - SEN_HILOGE("ReadFromParcel is failed"); + SEN_HILOGE("Read from parcel is failed"); return nullptr; } - auto subscribeInfo = std::make_unique(); - subscribeInfo->SetPid(pid); - subscribeInfo->SetSensorId(sensorId); - subscribeInfo->Enable(isActive); - subscribeInfo->SetSamplingPeriodNs(samplingPeriodNs); - subscribeInfo->SetMaxReportDelayNs(maxReportDelayNs); - return subscribeInfo; + auto activeInfo = std::make_unique(); + activeInfo->SetPid(pid); + activeInfo->SetSensorId(sensorId); + activeInfo->SetSamplingPeriodNs(samplingPeriodNs); + activeInfo->SetMaxReportDelayNs(maxReportDelayNs); + return activeInfo; } } // namespace Sensors } // namespace OHOS \ No newline at end of file -- Gitee From c409a3e0cd87db484f2baeac09893b7e3b5a6304 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 6 Mar 2023 09:58:28 +0000 Subject: [PATCH 07/53] =?UTF-8?q?=E9=87=8D=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: Ic66a250d1095b9f87949606710d5a1f2f7c519bf --- frameworks/native/sensor/BUILD.gn | 2 +- ...le_descriptor_listener.h => fd_listener.h} | 14 +- .../sensor/include/sensor_data_channel.h | 2 - .../sensor/include/sensor_service_client.h | 1 - ...escriptor_listener.cpp => fd_listener.cpp} | 12 +- .../native/sensor/src/sensor_agent_proxy.cpp | 1 - .../native/sensor/src/sensor_data_channel.cpp | 6 +- .../test/unittest/sensor_power_test.cpp | 137 +++++++++--------- services/sensor/include/client_info.h | 2 - services/sensor/include/sensor_service.h | 1 - services/sensor/src/client_info.cpp | 4 +- services/sensor/src/sensor_service.cpp | 3 +- 12 files changed, 86 insertions(+), 99 deletions(-) rename frameworks/native/sensor/include/{client_info_file_descriptor_listener.h => fd_listener.h} (71%) rename frameworks/native/sensor/src/{client_info_file_descriptor_listener.cpp => fd_listener.cpp} (85%) diff --git a/frameworks/native/sensor/BUILD.gn b/frameworks/native/sensor/BUILD.gn index 9fbac926..551a5c3b 100755 --- a/frameworks/native/sensor/BUILD.gn +++ b/frameworks/native/sensor/BUILD.gn @@ -18,6 +18,7 @@ SUBSYSTEM_DIR = "//base/sensors" ############################################## ohos_shared_library("libsensor_native") { sources = [ + "src/fd_listener.cpp", "src/sensor_agent_proxy.cpp", "src/sensor_client_stub.cpp", "src/sensor_data_channel.cpp", @@ -25,7 +26,6 @@ ohos_shared_library("libsensor_native") { "src/sensor_file_descriptor_listener.cpp", "src/sensor_service_client.cpp", "src/sensor_service_proxy.cpp", - "src/client_info_file_descriptor_listener.cpp", ] include_dirs = [ diff --git a/frameworks/native/sensor/include/client_info_file_descriptor_listener.h b/frameworks/native/sensor/include/fd_listener.h similarity index 71% rename from frameworks/native/sensor/include/client_info_file_descriptor_listener.h rename to frameworks/native/sensor/include/fd_listener.h index ec107974..76b45777 100644 --- a/frameworks/native/sensor/include/client_info_file_descriptor_listener.h +++ b/frameworks/native/sensor/include/fd_listener.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef CLIENT_INFO_FILE_DESCRIPTOR_LISTENER_H -#define CLIENT_INFO_FILE_DESCRIPTOR_LISTENER_H +#ifndef FD_LISTENER_H +#define FD_LISTENER_H #include "file_descriptor_listener.h" @@ -22,19 +22,19 @@ namespace OHOS { namespace Sensors { -class ClientInfoFileDescriptorListener : public AppExecFwk::FileDescriptorListener { +class FdListener : public AppExecFwk::FileDescriptorListener { public: - ClientInfoFileDescriptorListener() = default; - ~ClientInfoFileDescriptorListener() override = default; + FdListener() = default; + ~FdListener() override = default; void OnReadable(int32_t fd) override; void OnShutdown(int32_t fd) override; void OnException(int32_t fd) override; void SetChannel(SensorDataChannel *channel); - DISALLOW_COPY_AND_MOVE(ClientInfoFileDescriptorListener); + DISALLOW_COPY_AND_MOVE(FdListener); private: SensorDataChannel *channel_ = nullptr; }; } // namespace Sensors } // namespace OHOS -#endif // CLIENT_INFO_FILE_DESCRIPTOR_LISTENER_H +#endif // FD_LISTENER_H diff --git a/frameworks/native/sensor/include/sensor_data_channel.h b/frameworks/native/sensor/include/sensor_data_channel.h index 1b004337..f6ef699c 100644 --- a/frameworks/native/sensor/include/sensor_data_channel.h +++ b/frameworks/native/sensor/include/sensor_data_channel.h @@ -32,7 +32,6 @@ class SensorDataChannel : public SensorBasicDataChannel { public: using ReceiveMessageFun = std::function; using DisconnectFun = std::function; - SensorDataChannel() = default; ~SensorDataChannel(); static int32_t HandleEvent(int32_t fd, int32_t events, void *data); @@ -44,7 +43,6 @@ public: int32_t test = 10; DataChannelCB dataCB_ = nullptr; void *privateData_ = nullptr; - int32_t AddFdListener(int32_t fd, ReceiveMessageFun receiveMessage, DisconnectFun disconnect); int32_t DelFdListener(int32_t fd); ReceiveMessageFun receiveMessage_; diff --git a/frameworks/native/sensor/include/sensor_service_client.h b/frameworks/native/sensor/include/sensor_service_client.h index 85207e98..944a8cbc 100755 --- a/frameworks/native/sensor/include/sensor_service_client.h +++ b/frameworks/native/sensor/include/sensor_service_client.h @@ -70,7 +70,6 @@ private: void HandleNetPacke(NetPacket &pkt); std::atomic_bool isConnected_ = false; CircleStreamBuffer circBuf_; - std::mutex activeInfoCBMutex_; std::set activeInfoCBSet_; }; diff --git a/frameworks/native/sensor/src/client_info_file_descriptor_listener.cpp b/frameworks/native/sensor/src/fd_listener.cpp similarity index 85% rename from frameworks/native/sensor/src/client_info_file_descriptor_listener.cpp rename to frameworks/native/sensor/src/fd_listener.cpp index 4782e63a..cba25a92 100644 --- a/frameworks/native/sensor/src/client_info_file_descriptor_listener.cpp +++ b/frameworks/native/sensor/src/fd_listener.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "client_info_file_descriptor_listener.h" +#include "fd_listener.h" #include @@ -24,15 +24,15 @@ namespace OHOS { namespace Sensors { using namespace OHOS::AppExecFwk; namespace { -constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "ClientInfoFileDescriptorListener" }; +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "FdListener" }; } -void ClientInfoFileDescriptorListener::SetChannel(SensorDataChannel *channel) +void FdListener::SetChannel(SensorDataChannel *channel) { channel_ = channel; } -void ClientInfoFileDescriptorListener::OnReadable(int32_t fd) +void FdListener::OnReadable(int32_t fd) { if (fd < 0) { SEN_HILOGE("Invalid fd"); @@ -62,7 +62,7 @@ void ClientInfoFileDescriptorListener::OnReadable(int32_t fd) } } -void ClientInfoFileDescriptorListener::OnShutdown(int32_t fd) +void FdListener::OnShutdown(int32_t fd) { if (fd < 0) { SEN_HILOGE("Invalid fd"); @@ -70,7 +70,7 @@ void ClientInfoFileDescriptorListener::OnShutdown(int32_t fd) channel_->disconnect_(); } -void ClientInfoFileDescriptorListener::OnException(int32_t fd) +void FdListener::OnException(int32_t fd) { if (fd < 0) { SEN_HILOGE("Invalid fd"); diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index ebf42acc..fad8e862 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -18,7 +18,6 @@ #include #include "securec.h" - #include "sensor_service_client.h" #include "sensors_errors.h" diff --git a/frameworks/native/sensor/src/sensor_data_channel.cpp b/frameworks/native/sensor/src/sensor_data_channel.cpp index cc640755..27e4e058 100644 --- a/frameworks/native/sensor/src/sensor_data_channel.cpp +++ b/frameworks/native/sensor/src/sensor_data_channel.cpp @@ -17,14 +17,14 @@ #include "errors.h" -#include "client_info_file_descriptor_listener.h" +#include "fd_listener.h" #include "sensor_file_descriptor_listener.h" #include "sensors_errors.h" + namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; using namespace OHOS::AppExecFwk; - namespace { constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SensorDataChannel" }; } // namespace @@ -110,7 +110,7 @@ int32_t SensorDataChannel::AddFdListener(int32_t fd, ReceiveMessageFun receiveMe CHKPR(myRunner, ERROR); eventHandler_ = std::make_shared(myRunner); } - auto listener = std::make_shared(); + auto listener = std::make_shared(); listener->SetChannel(this); auto errCode = eventHandler_->AddFileDescriptorListener(fd, AppExecFwk::FILE_DESCRIPTOR_INPUT_EVENT, listener); if (errCode != ERR_OK) { diff --git a/interfaces/native/test/unittest/sensor_power_test.cpp b/interfaces/native/test/unittest/sensor_power_test.cpp index da5a3dfb..f37c3402 100644 --- a/interfaces/native/test/unittest/sensor_power_test.cpp +++ b/interfaces/native/test/unittest/sensor_power_test.cpp @@ -91,70 +91,68 @@ void SensorDataCallbackImpl(SensorEvent *event) event[0].sensorTypeId, event[0].version, event[0].dataLen, *(sensorData)); } -void ClientInfoCallbackImpl(SubscribeSensorInfo &subscribeSensorInfo) +void SensorActiveInfoCBImpl(SensorActiveInfo &sensorActiveInfo) { - SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " - "samplingPeriodNs:%{public}" PRId64 ", maxReportDelayNs:%{public}" PRId64 "", - subscribeSensorInfo.pid, subscribeSensorInfo.sensorId, subscribeSensorInfo.isActive, - subscribeSensorInfo.samplingPeriodNs, subscribeSensorInfo.maxReportDelayNs); + SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, samplingPeriodNs:%{public}" PRId64 ", " + "maxReportDelayNs:%{public}" PRId64 "", sensorActiveInfo.pid, sensorActiveInfo.sensorId, + sensorActiveInfo.samplingPeriodNs, sensorActiveInfo.maxReportDelayNs); } -void ClientInfoCallbackImpl2(SubscribeSensorInfo &subscribeSensorInfo) +void SensorActiveInfoCBImpl2(SensorActiveInfo &sensorActiveInfo) { - SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " - "samplingPeriodNs:%{public}" PRId64 ", maxReportDelayNs:%{public}" PRId64 "", - subscribeSensorInfo.pid, subscribeSensorInfo.sensorId, subscribeSensorInfo.isActive, - subscribeSensorInfo.samplingPeriodNs, subscribeSensorInfo.maxReportDelayNs); + SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, samplingPeriodNs:%{public}" PRId64 ", " + "maxReportDelayNs:%{public}" PRId64 "", sensorActiveInfo.pid, sensorActiveInfo.sensorId, + sensorActiveInfo.samplingPeriodNs, sensorActiveInfo.maxReportDelayNs); } -HWTEST_F(SensorPowerTest, SuspendSensorsTest_001, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_001, TestSize.Level1) { // 休眠接口异常用例 - SEN_HILOGI("SuspendSensorsTest_001 in"); + SEN_HILOGI("SensorPowerTest_001 in"); int32_t ret = SuspendSensors(invalidValue); ASSERT_NE(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, ResumeSensorsTest_001, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_002, TestSize.Level1) { // 恢复接口异常用例 - SEN_HILOGI("ResumeSensorsTest_001 in"); + SEN_HILOGI("SensorPowerTest_002 in"); int32_t ret = ResumeSensors(invalidValue); ASSERT_NE(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, GetSubscribeInfosTest_001, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_003, TestSize.Level1) { // 查询接口异常用例 - SEN_HILOGI("GetSubscribeInfosTest_001 in"); - SubscribeSensorInfo *subscribeSensorInfo {nullptr}; + SEN_HILOGI("SensorPowerTest_003 in"); + SensorActiveInfo *sensorActiveInfos {nullptr}; int32_t count { 0 }; - int32_t ret = GetSubscribeInfos(invalidValue, &subscribeSensorInfo, &count); + int32_t ret = GetSensorActiveInfos(invalidValue, &sensorActiveInfos, &count); ASSERT_NE(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, RegisterClientInfoCallback_001, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_004, TestSize.Level1) { // 注册接口异常用例 - SEN_HILOGI("RegisterClientInfoCallback_001 in"); - ClientInfoCallback callback = nullptr; - int32_t ret = RegisterClientInfoCallback(callback); + SEN_HILOGI("SensorPowerTest_004 in"); + SensorActiveInfoCB callback = nullptr; + int32_t ret = RegisterSensorActiveInfoCB(callback); ASSERT_NE(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, UnregisterClientInfoCallback_001, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_005, TestSize.Level1) { // 取消注册接口异常用例 - SEN_HILOGI("UnregisterClientInfoCallback_001 in"); - ClientInfoCallback callback = nullptr; - int32_t ret = UnregisterClientInfoCallback(callback); + SEN_HILOGI("SensorPowerTest_005 in"); + SensorActiveInfoCB callback = nullptr; + int32_t ret = UnregisterSensorActiveInfoCB(callback); ASSERT_NE(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, SensorPowerTest_001, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_006, TestSize.Level1) { // 场景用例1,订阅ACC传感器》查询传感器订阅数据》休眠进程的传感器》恢复进程的传感器》取消订阅ACC传感器 - SEN_HILOGI("SensorPowerTest_001 in"); + SEN_HILOGI("SensorPowerTest_006 in"); SensorUser user; user.callback = SensorDataCallbackImpl; @@ -166,15 +164,14 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_001, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); std::this_thread::sleep_for(std::chrono::milliseconds(500)); - SubscribeSensorInfo *subscribeSensorInfo {nullptr}; + SensorActiveInfo *sensorActiveInfos {nullptr}; int32_t count { 0 }; - ret = GetSubscribeInfos(process_pid, &subscribeSensorInfo, &count); + ret = GetSensorActiveInfos(process_pid, &sensorActiveInfos, &count); for (int32_t i = 0; i < count; ++i) { - SubscribeSensorInfo *curSubscribeSensorInfo = subscribeSensorInfo + i; - SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " - "samplingPeriodNs:%{public}" PRId64 ", maxReportDelayNs:%{public}" PRId64 "", - i, curSubscribeSensorInfo->pid, curSubscribeSensorInfo->sensorId, curSubscribeSensorInfo->isActive, - curSubscribeSensorInfo->samplingPeriodNs, curSubscribeSensorInfo->maxReportDelayNs); + SensorActiveInfo *curSensorActiveInfo = sensorActiveInfos + i; + SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, samplingPeriodNs:%{public}" PRId64 ", " + "maxReportDelayNs:%{public}" PRId64 "", curSensorActiveInfo->pid, curSensorActiveInfo->sensorId, + curSensorActiveInfo->samplingPeriodNs, curSensorActiveInfo->maxReportDelayNs); } ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); @@ -192,10 +189,10 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_001, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, SensorPowerTest_002, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_007, TestSize.Level1) { // 场景用例2,订阅ACC传感器》休眠进程的传感器》查询传感器订阅数据》恢复进程的传感器》取消订阅ACC传感器 - SEN_HILOGI("SensorPowerTest_002 in"); + SEN_HILOGI("SensorPowerTest_007 in"); SensorUser user; user.callback = SensorDataCallbackImpl; @@ -211,15 +208,14 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_002, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); std::this_thread::sleep_for(std::chrono::milliseconds(3000)); - SubscribeSensorInfo *subscribeSensorInfo {nullptr}; + SensorActiveInfo *sensorActiveInfos {nullptr}; int32_t count { 0 }; - ret = GetSubscribeInfos(process_pid, &subscribeSensorInfo, &count); + ret = GetSensorActiveInfos(process_pid, &sensorActiveInfos, &count); for (int32_t i = 0; i < count; ++i) { - SubscribeSensorInfo *curSubscribeSensorInfo = subscribeSensorInfo + i; - SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " - "samplingPeriodNs:%{public}" PRId64 ", maxReportDelayNs:%{public}" PRId64 "", - i, curSubscribeSensorInfo->pid, curSubscribeSensorInfo->sensorId, curSubscribeSensorInfo->isActive, - curSubscribeSensorInfo->samplingPeriodNs, curSubscribeSensorInfo->maxReportDelayNs); + SensorActiveInfo *curSensorActiveInfo = sensorActiveInfos + i; + SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, samplingPeriodNs:%{public}" PRId64 ", " + "maxReportDelayNs:%{public}" PRId64 "", curSensorActiveInfo->pid, curSensorActiveInfo->sensorId, + curSensorActiveInfo->samplingPeriodNs, curSensorActiveInfo->maxReportDelayNs); } ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); @@ -233,10 +229,10 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_002, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, SensorPowerTest_003, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_008, TestSize.Level1) { // 场景用例3,订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》查询传感器订阅数据》取消订阅ACC传感器 - SEN_HILOGI("SensorPowerTest_003 in"); + SEN_HILOGI("SensorPowerTest_008 in"); SensorUser user; user.callback = SensorDataCallbackImpl; @@ -256,15 +252,14 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_003, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); - SubscribeSensorInfo *subscribeSensorInfo {nullptr}; + SensorActiveInfo *sensorActiveInfos {nullptr}; int32_t count { 0 }; - ret = GetSubscribeInfos(process_pid, &subscribeSensorInfo, &count); + ret = GetSensorActiveInfos(process_pid, &sensorActiveInfos, &count); for (int32_t i = 0; i < count; ++i) { - SubscribeSensorInfo *curSubscribeSensorInfo = subscribeSensorInfo + i; - SEN_HILOGI("i:%{public}d, pid:%{public}d, sensorId:%{public}d, isActive:%{public}d, " - "samplingPeriodNs:%{public}" PRId64 ", maxReportDelayNs:%{public}" PRId64 "", - i, curSubscribeSensorInfo->pid, curSubscribeSensorInfo->sensorId, curSubscribeSensorInfo->isActive, - curSubscribeSensorInfo->samplingPeriodNs, curSubscribeSensorInfo->maxReportDelayNs); + SensorActiveInfo *curSensorActiveInfo = sensorActiveInfos + i; + SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, samplingPeriodNs:%{public}" PRId64 ", " + "maxReportDelayNs:%{public}" PRId64 "", curSensorActiveInfo->pid, curSensorActiveInfo->sensorId, + curSensorActiveInfo->samplingPeriodNs, curSensorActiveInfo->maxReportDelayNs); } ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); @@ -274,15 +269,15 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_003, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, SensorPowerTest_004, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_009, TestSize.Level1) { // 场景用例4,注册回调函数》订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》取消订阅ACC传感器》取消注册回调函数 - SEN_HILOGI("SensorPowerTest_004 in"); + SEN_HILOGI("SensorPowerTest_009 in"); SensorUser user; user.callback = SensorDataCallbackImpl; - ClientInfoCallback callback = ClientInfoCallbackImpl; + SensorActiveInfoCB callback = SensorActiveInfoCBImpl; - int32_t ret = RegisterClientInfoCallback(callback); + int32_t ret = RegisterSensorActiveInfoCB(callback); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); ret = SubscribeSensor(sensorId, &user); @@ -306,19 +301,19 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_004, TestSize.Level1) ret = UnsubscribeSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = UnregisterClientInfoCallback(callback); + ret = UnregisterSensorActiveInfoCB(callback); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, SensorPowerTest_005, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_010, TestSize.Level1) { // 场景用例5,注册回调函数》订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》取消注册回调函数》取消订阅ACC传感器 - SEN_HILOGI("SensorPowerTest_005 in"); + SEN_HILOGI("SensorPowerTest_010 in"); SensorUser user; user.callback = SensorDataCallbackImpl; - ClientInfoCallback callback = ClientInfoCallbackImpl; + SensorActiveInfoCB callback = SensorActiveInfoCBImpl; - int32_t ret = RegisterClientInfoCallback(callback); + int32_t ret = RegisterSensorActiveInfoCB(callback); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); ret = SubscribeSensor(sensorId, &user); @@ -340,25 +335,25 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_005, TestSize.Level1) ret = DeactivateSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = UnregisterClientInfoCallback(callback); + ret = UnregisterSensorActiveInfoCB(callback); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); ret = UnsubscribeSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, SensorPowerTest_006, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_011, TestSize.Level1) { // 场景用例6,注册回调函数1》注册回调函数2》订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》取消订阅ACC传感器》取消注册回调函数1》取消注册回调函数2 - SEN_HILOGI("SensorPowerTest_006 in"); + SEN_HILOGI("SensorPowerTest_011 in"); SensorUser user; user.callback = SensorDataCallbackImpl; - ClientInfoCallback callback = ClientInfoCallbackImpl; - ClientInfoCallback callback2 = ClientInfoCallbackImpl2; + SensorActiveInfoCB callback = SensorActiveInfoCBImpl; + SensorActiveInfoCB callback2 = SensorActiveInfoCBImpl2; - int32_t ret = RegisterClientInfoCallback(callback); + int32_t ret = RegisterSensorActiveInfoCB(callback); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = RegisterClientInfoCallback(callback2); + ret = RegisterSensorActiveInfoCB(callback2); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); ret = SubscribeSensor(sensorId, &user); @@ -382,9 +377,9 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_006, TestSize.Level1) ret = UnsubscribeSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = UnregisterClientInfoCallback(callback); + ret = UnregisterSensorActiveInfoCB(callback); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = UnregisterClientInfoCallback(callback2); + ret = UnregisterSensorActiveInfoCB(callback2); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); } } // namespace Sensors diff --git a/services/sensor/include/client_info.h b/services/sensor/include/client_info.h index f35164db..61bc61a3 100644 --- a/services/sensor/include/client_info.h +++ b/services/sensor/include/client_info.h @@ -75,7 +75,6 @@ public: void ClearDataQueue(int32_t sensorId); int32_t GetUidByPid(int32_t pid); AccessTokenID GetTokenIdByPid(int32_t pid); - int32_t AddActiveInfoCBPid(int32_t pid); int32_t DelActiveInfoCBPid(int32_t pid); std::unordered_set GetActiveInfoCBPid(); @@ -98,7 +97,6 @@ private: std::map, int32_t> clientPidMap_; std::unordered_map>> cmdMap_; std::unordered_map> dumpQueue_; - std::mutex activeInfoCBPidMutex_; std::unordered_set activeInfoCBPidSet_; }; diff --git a/services/sensor/include/sensor_service.h b/services/sensor/include/sensor_service.h index ab5073b9..162ef878 100644 --- a/services/sensor/include/sensor_service.h +++ b/services/sensor/include/sensor_service.h @@ -92,7 +92,6 @@ private: // death recipient of sensor client sptr clientDeathObserver_ = nullptr; ErrCode SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); - std::atomic_bool isReportActiveInfo_ = false; void ReportActiveInfo(int32_t sensorId, int32_t pid); }; diff --git a/services/sensor/src/client_info.cpp b/services/sensor/src/client_info.cpp index c53cb768..afdb3261 100644 --- a/services/sensor/src/client_info.cpp +++ b/services/sensor/src/client_info.cpp @@ -718,13 +718,13 @@ bool ClientInfo::IsUnregisterClientDeathRecipient(int32_t pid) std::lock_guard channelLock(channelMutex_); auto channelIt = channelMap_.find(pid); if (channelIt != channelMap_.end()) { - SEN_HILOGD("pid exist in channelMap"); + SEN_HILOGD("Pid exist in channelMap"); return false; } std::lock_guard activeInfoCBPidLock(activeInfoCBPidMutex_); auto pidIt = activeInfoCBPidSet_.find(pid); if (pidIt != activeInfoCBPidSet_.end()) { - SEN_HILOGD("pid exist in activeInfoCBPidSet"); + SEN_HILOGD("Pid exist in activeInfoCBPidSet"); return false; } return true; diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 4ce764f9..9add4a60 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -26,7 +26,6 @@ #include "permission_util.h" #include "securec.h" #include "sensor.h" -#include "sensor_agent_type.h" #include "sensor_dump.h" #include "sensors_errors.h" #include "system_ability_definition.h" @@ -366,7 +365,7 @@ void SensorService::ProcessDeathObserver(const wptr &object) } } DelSession(pid); - clientInfo_.DelClientInfoCallbackPid(pid); + clientInfo_.DelActiveInfoCBPid(pid); clientInfo_.DestroySensorChannel(pid); clientInfo_.DestroyClientPid(client); clientInfo_.DestroyCmd(clientInfo_.GetUidByPid(pid)); -- Gitee From b4585979fdb2feab78e3ae3502901ace53646946 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 6 Mar 2023 10:13:49 +0000 Subject: [PATCH 08/53] Signed-off-by: hui1975 Change-Id: If13682c9ecf460f197bc69b411b5b9f6413ab807 --- interfaces/native/test/unittest/sensor_power_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/native/test/unittest/sensor_power_test.cpp b/interfaces/native/test/unittest/sensor_power_test.cpp index f37c3402..5f197cac 100644 --- a/interfaces/native/test/unittest/sensor_power_test.cpp +++ b/interfaces/native/test/unittest/sensor_power_test.cpp @@ -217,7 +217,7 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_007, TestSize.Level1) "maxReportDelayNs:%{public}" PRId64 "", curSensorActiveInfo->pid, curSensorActiveInfo->sensorId, curSensorActiveInfo->samplingPeriodNs, curSensorActiveInfo->maxReportDelayNs); } - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ASSERT_NE(ret, OHOS::Sensors::SUCCESS); ret = ResumeSensors(process_pid); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); -- Gitee From 13207bf9f1169f30d6a801faf9b3ef18b9f3c121 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 6 Mar 2023 11:38:32 +0000 Subject: [PATCH 09/53] fix bug Signed-off-by: hui1975 Change-Id: If1653c3b054e3303af7c29dbcc878284f6c6dcb8 --- frameworks/native/sensor/src/sensor_agent_proxy.cpp | 4 ++-- interfaces/native/test/unittest/sensor_power_test.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index fad8e862..f8f72c7c 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -386,8 +386,8 @@ int32_t SensorAgentProxy::GetSensorActiveInfos(int32_t pid, SensorActiveInfo **s return ret; } if (activeInfoList.empty()) { - SEN_HILOGE("Active info list is empty"); - return ERROR; + SEN_HILOGD("Active info list is empty"); + return ERR_OK; } size_t activeInfoCount = activeInfoList.size(); if (activeInfoCount > MAX_SENSOR_LIST_SIZE) { diff --git a/interfaces/native/test/unittest/sensor_power_test.cpp b/interfaces/native/test/unittest/sensor_power_test.cpp index 5f197cac..f37c3402 100644 --- a/interfaces/native/test/unittest/sensor_power_test.cpp +++ b/interfaces/native/test/unittest/sensor_power_test.cpp @@ -217,7 +217,7 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_007, TestSize.Level1) "maxReportDelayNs:%{public}" PRId64 "", curSensorActiveInfo->pid, curSensorActiveInfo->sensorId, curSensorActiveInfo->samplingPeriodNs, curSensorActiveInfo->maxReportDelayNs); } - ASSERT_NE(ret, OHOS::Sensors::SUCCESS); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); ret = ResumeSensors(process_pid); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); -- Gitee From 69c78437f097cbcb1d6faa91640e73ad4eacf577 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 6 Mar 2023 13:39:23 +0000 Subject: [PATCH 10/53] update Signed-off-by: hui1975 Change-Id: Ida60e5159e2b9449ce8a60d2e78830ea9c4cd952 --- .../sensor/src/sensor_service_client.cpp | 4 +- services/sensor/src/sensor_suspend_policy.cpp | 2 +- utils/common/BUILD.gn | 2 +- utils/ipc/BUILD.gn | 1 - utils/ipc/include/proto.h | 2 +- utils/ipc/include/stream_client.h | 55 -------- utils/ipc/src/stream_client.cpp | 122 ------------------ 7 files changed, 5 insertions(+), 183 deletions(-) delete mode 100644 utils/ipc/include/stream_client.h delete mode 100644 utils/ipc/src/stream_client.cpp diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index df592125..e4240993 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -346,8 +346,8 @@ void SensorServiceClient::ReceiveMessage(const char *buf, size_t size) void SensorServiceClient::HandleNetPacke(NetPacket &pkt) { auto id = pkt.GetMsgId(); - if (id != MessageId::CLIENT_INFO) { - SEN_HILOGE("NetPacke message id is not CLIENT_INFO"); + if (id != MessageId::ACTIVE_INFO) { + SEN_HILOGE("NetPacke message id is not ACTIVE_INFO"); return; } SensorActiveInfo sensorActiveInfo; diff --git a/services/sensor/src/sensor_suspend_policy.cpp b/services/sensor/src/sensor_suspend_policy.cpp index 02edb18c..140aec9b 100644 --- a/services/sensor/src/sensor_suspend_policy.cpp +++ b/services/sensor/src/sensor_suspend_policy.cpp @@ -205,7 +205,7 @@ void SensorSuspendPolicy::ReportActiveInfo(ActiveInfo activeInfo, const std::vector &sessionList) { CALL_LOG_ENTER; - NetPacket pkt(MessageId::CLIENT_INFO); + NetPacket pkt(MessageId::ACTIVE_INFO); pkt << activeInfo.GetPid() << activeInfo.GetSensorId() << activeInfo.GetSamplingPeriodNs() << activeInfo.GetMaxReportDelayNs(); if (pkt.ChkRWError()) { diff --git a/utils/common/BUILD.gn b/utils/common/BUILD.gn index 64b32943..0afec250 100644 --- a/utils/common/BUILD.gn +++ b/utils/common/BUILD.gn @@ -15,13 +15,13 @@ import("//build/ohos.gni") ohos_shared_library("libsensor_utils") { sources = [ + "src/active_info.cpp", "src/permission_util.cpp", "src/report_data_callback.cpp", "src/sensor.cpp", "src/sensor_basic_data_channel.cpp", "src/sensor_basic_info.cpp", "src/sensor_channel_info.cpp", - "src/active_info.cpp", ] include_dirs = [ diff --git a/utils/ipc/BUILD.gn b/utils/ipc/BUILD.gn index 3b78d1ff..6e579be0 100644 --- a/utils/ipc/BUILD.gn +++ b/utils/ipc/BUILD.gn @@ -18,7 +18,6 @@ ohos_shared_library("libsensor_ipc") { "src/circle_stream_buffer.cpp", "src/net_packet.cpp", "src/stream_buffer.cpp", - "src/stream_client.cpp", "src/stream_session.cpp", "src/stream_socket.cpp", ] diff --git a/utils/ipc/include/proto.h b/utils/ipc/include/proto.h index 207b8640..5b074be4 100644 --- a/utils/ipc/include/proto.h +++ b/utils/ipc/include/proto.h @@ -40,7 +40,7 @@ static const int32_t PROTO_ONCE_PROCESS_NETPACKET_LIMIT = 100; enum class MessageId : int32_t { INVALID, - CLIENT_INFO, + ACTIVE_INFO, }; } // namespace Sensors } // namespace OHOS diff --git a/utils/ipc/include/stream_client.h b/utils/ipc/include/stream_client.h deleted file mode 100644 index 4dd9a1e9..00000000 --- a/utils/ipc/include/stream_client.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef STREAM_CLIENT_H -#define STREAM_CLIENT_H - -#include -#include -#include - -#include "nocopyable.h" - -#include "net_packet.h" -#include "stream_socket.h" - -namespace OHOS { -namespace Sensors { -class StreamClient; -using MsgClientFunCallback = std::function; -class StreamClient : public StreamSocket { -public: - StreamClient(); - virtual ~StreamClient(); - virtual int32_t Socket() = 0; - virtual void Stop(); - int32_t ConnectTo(); - bool SendMsg(const char *buf, size_t size) const; - bool SendMsg(const NetPacket &pkt) const; - bool GetConnectedStatus() const; - DISALLOW_COPY_AND_MOVE(StreamClient); - -protected: - virtual void OnConnected() {} - virtual void OnDisconnected() {} - bool StartClient(MsgClientFunCallback fun); - bool isExit { false }; - bool isRunning_ { false }; - bool isConnected_ { false }; - MsgClientFunCallback recvFun_; -}; -} // namespace Sensors -} // namespace OHOS -#endif // STREAM_CLIENT_H \ No newline at end of file diff --git a/utils/ipc/src/stream_client.cpp b/utils/ipc/src/stream_client.cpp deleted file mode 100644 index 4e1fedf9..00000000 --- a/utils/ipc/src/stream_client.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "stream_client.h" - -#include "sensors_errors.h" - -namespace OHOS { -namespace Sensors { -namespace { -constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "StreamClient" }; -} - -StreamClient::StreamClient() {} - -StreamClient::~StreamClient() {} - -int32_t StreamClient::ConnectTo() -{ - CALL_LOG_ENTER; - if (Socket() < 0) { - SEN_HILOGE("Socket failed"); - return ERROR; - } - OnConnected(); - return SUCCESS; -} - -bool StreamClient::SendMsg(const char *buf, size_t size) const -{ - CALL_LOG_ENTER; - CHKPF(buf); - if ((size == 0) || (size > PROTO_MAX_PACKET_BUF_SIZE)) { - SEN_HILOGE("Stream buffer size out of range"); - return false; - } - if (fd_ < 0) { - SEN_HILOGE("The fd_ is less than 0"); - return false; - } - int32_t idx = 0; - int32_t retryCount = 0; - const int32_t bufSize = static_cast(size); - int32_t remSize = bufSize; - while (remSize > 0 && retryCount < PROTO_SEND_RETRY_LIMIT) { - retryCount += 1; - auto count = send(fd_, &buf[idx], remSize, MSG_DONTWAIT | MSG_NOSIGNAL); - if (count < 0) { - if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) { - SEN_HILOGW("Continue for errno EAGAIN|EINTR|EWOULDBLOCK, errno:%{public}d", errno); - continue; - } - SEN_HILOGE("Send return failed,error:%{public}d fd:%{public}d", errno, fd_); - return false; - } - idx += count; - remSize -= count; - if (remSize > 0) { - usleep(PROTO_SEND_RETRY_SLEEP_TIME); - } - } - if (retryCount >= PROTO_SEND_RETRY_LIMIT || remSize != 0) { - SEN_HILOGE("Send too many times:%{public}d/%{public}d,size:%{public}d/%{public}d fd:%{public}d", - retryCount, PROTO_SEND_RETRY_LIMIT, idx, bufSize, fd_); - return false; - } - return true; -} - -bool StreamClient::SendMsg(const NetPacket &pkt) const -{ - CALL_LOG_ENTER; - if (pkt.ChkRWError()) { - SEN_HILOGE("Read and write status is error"); - return false; - } - StreamBuffer buf; - pkt.MakeData(buf); - return SendMsg(buf.Data(), buf.Size()); -} - -bool StreamClient::StartClient(MsgClientFunCallback fun) -{ - CALL_LOG_ENTER; - if (isRunning_ || isConnected_) { - SEN_HILOGE("Client is connected or started"); - return false; - } - isExit = false; - recvFun_ = fun; - if (ConnectTo() < 0) { - SEN_HILOGW("Client connection failed, Try again later"); - } - return true; -} - -void StreamClient::Stop() -{ - CALL_LOG_ENTER; - isExit = true; - isRunning_ = false; - Close(); -} - -bool StreamClient::GetConnectedStatus() const -{ - return isConnected_; -} -} // namespace Sensors -} // namespace OHOS \ No newline at end of file -- Gitee From 48bc60bbe2ca5ae69d4bc736f16a7b450ffe3fb3 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Tue, 7 Mar 2023 03:39:59 +0000 Subject: [PATCH 11/53] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: I24e072051124454d39b40234dc039bcce51c837d --- utils/ipc/src/stream_buffer.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/utils/ipc/src/stream_buffer.cpp b/utils/ipc/src/stream_buffer.cpp index a586ef72..04929262 100644 --- a/utils/ipc/src/stream_buffer.cpp +++ b/utils/ipc/src/stream_buffer.cpp @@ -185,11 +185,9 @@ const std::string &StreamBuffer::GetErrorStatusRemark() const }; static const std::string invalidStatus { "UNKNOWN" }; - auto tIter = std::find_if(remark.cbegin(), remark.cend(), - [this](const auto &item) { - return (item.first == rwErrorStatus_); - } - ); + auto tIter = std::find_if(remark.cbegin(), remark.cend(), [this](const auto &item) { + return (item.first == rwErrorStatus_); + }); return (tIter != remark.cend() ? tIter->second : invalidStatus); } -- Gitee From 2b1337c353fd094553142c3b99d81bb73d26dbea Mon Sep 17 00:00:00 2001 From: hui1975 Date: Tue, 7 Mar 2023 08:30:36 +0000 Subject: [PATCH 12/53] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: Idd5fec8dbd27e9e0e29d0346a5a01218d699a1ab --- .../sensor/include/sensor_suspend_policy.h | 15 +-- services/sensor/src/sensor_service.cpp | 3 +- services/sensor/src/sensor_suspend_policy.cpp | 110 ++++++++---------- 3 files changed, 56 insertions(+), 72 deletions(-) diff --git a/services/sensor/include/sensor_suspend_policy.h b/services/sensor/include/sensor_suspend_policy.h index a270beb1..23090724 100644 --- a/services/sensor/include/sensor_suspend_policy.h +++ b/services/sensor/include/sensor_suspend_policy.h @@ -22,13 +22,12 @@ #include "nocopyable.h" +#include "active_info.h" #include "client_info.h" -#include "sensor_agent_type.h" #include "sensor_hdi_connection.h" #include "sensor_manager.h" #include "sensors_errors.h" #include "stream_session.h" -#include "active_info.h" namespace OHOS { namespace Sensors { @@ -36,17 +35,15 @@ class SensorSuspendPolicy : public Singleton{ public: ErrCode SuspendSensors(int32_t pid); ErrCode ResumeSensors(int32_t pid); - ErrCode GetActiveInfoList(int32_t pid, std::vector &activeInfoList); + void GetActiveInfoList(int32_t pid, std::vector &activeInfoList); void ReportActiveInfo(ActiveInfo activeInfo, const std::vector &sessionList); private: bool CheckFreezingSensor(int32_t sensorId); - bool DisableSensorList(std::unordered_map &SensorInfoMap, - std::vector &sensorIdList, int32_t pid); - ErrCode DisableSensor(std::unordered_map &SensorInfoMap, - int32_t sensorId, int32_t pid); - ErrCode EnableSensor(int32_t sensorId, int32_t pid, int64_t samplingPeriodNs, int64_t maxReportDelayNs); - ErrCode RestoreSensorInfo(int32_t sensorId, int32_t pid, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + bool Suspend(std::unordered_map &SensorInfoMap, + std::vector &sensorIdList, int32_t pid); + bool Resume(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + ErrCode RestoreSensorInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); SensorHdiConnection &sensorHdiConnection_ = SensorHdiConnection::GetInstance(); ClientInfo &clientInfo_ = ClientInfo::GetInstance(); SensorManager &sensorManager_ = SensorManager::GetInstance(); diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 9add4a60..b7e04dee 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -450,7 +450,8 @@ ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector &a SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } - return suspendPolicy_.GetActiveInfoList(pid, activeInfoList); + suspendPolicy_.GetActiveInfoList(pid, activeInfoList); + return ERR_OK; } ErrCode SensorService::CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) diff --git a/services/sensor/src/sensor_suspend_policy.cpp b/services/sensor/src/sensor_suspend_policy.cpp index 140aec9b..33b729e1 100644 --- a/services/sensor/src/sensor_suspend_policy.cpp +++ b/services/sensor/src/sensor_suspend_policy.cpp @@ -46,8 +46,8 @@ ErrCode SensorSuspendPolicy::SuspendSensors(int32_t pid) } else { SEN_HILOGD("Pid already suspend, some sensors suspend failed, suspend these sensors again"); std::unordered_map SensorInfoMap = pidSensorInfoIt->second; - if (!DisableSensorList(SensorInfoMap, sensorIdList, pid)) { - SEN_HILOGE("Some sensor disable failed"); + if (!Suspend(SensorInfoMap, sensorIdList, pid)) { + SEN_HILOGE("Some sensor suspend failed"); return DISABLE_SENSOR_ERR; } return ERR_OK; @@ -58,53 +58,40 @@ ErrCode SensorSuspendPolicy::SuspendSensors(int32_t pid) return ERROR; } std::unordered_map SensorInfoMap; - bool suspendAllSensors = DisableSensorList(SensorInfoMap, sensorIdList, pid); + auto isAllSuspend = Suspend(SensorInfoMap, sensorIdList, pid); pidSensorInfoMap_.insert(std::make_pair(pid, SensorInfoMap)); - if (!suspendAllSensors) { - SEN_HILOGE("Some sensor disable failed"); + if (!isAllSuspend) { + SEN_HILOGE("Some sensor suspend failed"); return DISABLE_SENSOR_ERR; } return ERR_OK; } -bool SensorSuspendPolicy::DisableSensorList(std::unordered_map &SensorInfoMap, - std::vector &sensorIdList, int32_t pid) +bool SensorSuspendPolicy::Suspend(std::unordered_map &SensorInfoMap, + std::vector &sensorIdList, int32_t pid) { CALL_LOG_ENTER; - bool suspendAllSensors = true; + bool isAllSuspend = true; for (auto &sensorId : sensorIdList) { if (CheckFreezingSensor(sensorId)) { + SEN_HILOGD("Current sensor is pedometer detectio or pedometer, can not suspend"); continue; } - auto ret = DisableSensor(SensorInfoMap, sensorId, pid); - if (ret != ERR_OK) { - SEN_HILOGE("Disable Sensor is failed. sensorId:%{public}d, ret:%{public}d", sensorId, ret); - suspendAllSensors = false; + auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); + if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { + SEN_HILOGD("Other client is using this sensor now, cannot suspend"); + SensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); + continue; + } + if (sensorHdiConnection_.DisableSensor(sensorId) != ERR_OK) { + SEN_HILOGE("Disable sensor failed, sensorId:%{public}d", sensorId); + isAllSuspend = false; + continue; } - } - return suspendAllSensors; -} - -ErrCode SensorSuspendPolicy::DisableSensor(std::unordered_map &SensorInfoMap, - int32_t sensorId, int32_t pid) -{ - CALL_LOG_ENTER; - if (sensorId == INVALID_SENSOR_ID) { - SEN_HILOGE("SensorId is invalid"); - return ERR_NO_INIT; - } - auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); - if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { - SEN_HILOGW("Other client is using this sensor now, cannot disable"); SensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); - return ERR_OK; - } - if (sensorHdiConnection_.DisableSensor(sensorId) != ERR_OK) { - SEN_HILOGE("DisableSensor is failed"); - return DISABLE_SENSOR_ERR; + sensorManager_.AfterDisableSensor(sensorId); } - SensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); - return sensorManager_.AfterDisableSensor(sensorId); + return isAllSuspend; } ErrCode SensorSuspendPolicy::ResumeSensors(int32_t pid) @@ -116,79 +103,79 @@ ErrCode SensorSuspendPolicy::ResumeSensors(int32_t pid) SEN_HILOGE("Pid not have suspend sensors"); return ERROR; } - bool resumeAllSensors = true; + bool isAllResume = true; std::unordered_map SensorInfoMap = pidSensorInfoIt->second; for (auto sensorIt = SensorInfoMap.begin(); sensorIt != SensorInfoMap.end();) { int32_t sensorId = sensorIt->first; int64_t samplingPeriodNs = sensorIt->second.GetSamplingPeriodNs(); int64_t maxReportDelayNs = sensorIt->second.GetMaxReportDelayNs(); - auto ret = EnableSensor(sensorId, pid, samplingPeriodNs, maxReportDelayNs); - if (ret != ERR_OK) { - SEN_HILOGE("Enable Sensor is failed. sensorId:%{public}d, ret:%{public}d", sensorId, ret); - resumeAllSensors = false; + if (!Resume(pid, sensorId, samplingPeriodNs, maxReportDelayNs)) { + SEN_HILOGE("Resume sensor failed. sensorId:%{public}d", sensorId); + isAllResume = false; ++sensorIt; } else { sensorIt = SensorInfoMap.erase(sensorIt); } } - if (!resumeAllSensors) { - SEN_HILOGE("Some sensor enable failed"); + if (!isAllResume) { + SEN_HILOGE("Some sensor resume failed"); return ENABLE_SENSOR_ERR; } pidSensorInfoMap_.erase(pidSensorInfoIt); return ERR_OK; } -ErrCode SensorSuspendPolicy::EnableSensor(int32_t sensorId, int32_t pid, int64_t samplingPeriodNs, - int64_t maxReportDelayNs) +bool SensorSuspendPolicy::Resume(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) { CALL_LOG_ENTER; if ((sensorId == INVALID_SENSOR_ID) || (samplingPeriodNs == 0) || ((samplingPeriodNs != 0L) && (maxReportDelayNs / samplingPeriodNs > MAX_EVENT_COUNT))) { - SEN_HILOGE("SensorId is 0 or maxReportDelayNs exceed the maximum value"); - return ERR_NO_INIT; + SEN_HILOGE("SensorId is invalid or maxReportDelayNs exceed the maximum value"); + return false; } if (clientInfo_.GetSensorState(sensorId)) { - SEN_HILOGD("Sensor has been enabled already, sensorId: %{public}d", sensorId); - auto ret = RestoreSensorInfo(sensorId, pid, samplingPeriodNs, maxReportDelayNs); + SEN_HILOGD("Sensor has been resume already, sensorId:%{public}d", sensorId); + auto ret = RestoreSensorInfo(pid, sensorId, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { - SEN_HILOGE("RestoreSensorInfo is failed, ret: %{public}d", ret); - return ret; + SEN_HILOGE("Restore sensor info failed, ret:%{public}d", ret); + return false; } - return ERR_OK; + return true; } - auto ret = RestoreSensorInfo(sensorId, pid, samplingPeriodNs, maxReportDelayNs); + auto ret = RestoreSensorInfo(pid, sensorId, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { - SEN_HILOGE("RestoreSensorInfo is failed, ret: %{public}d", ret); - return ret; + SEN_HILOGE("Restore sensor info failed, ret:%{public}d", ret); + return false; } ret = sensorHdiConnection_.EnableSensor(sensorId); if (ret != ERR_OK) { - SEN_HILOGE("EnableSensor is failed, ret: %{public}d", ret); + SEN_HILOGE("Resume sensor failed, ret:%{public}d", ret); clientInfo_.RemoveSubscriber(sensorId, pid); - return ENABLE_SENSOR_ERR; + return false; } - return ERR_OK; + return true; } -ErrCode SensorSuspendPolicy::RestoreSensorInfo(int32_t sensorId, int32_t pid, int64_t samplingPeriodNs, +ErrCode SensorSuspendPolicy::RestoreSensorInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) { + CALL_LOG_ENTER; auto ret = sensorManager_.SaveSubscriber(sensorId, pid, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { - SEN_HILOGE("RestoreSensorInfo is failed, ret: %{public}d", ret); + SEN_HILOGE("SaveSubscriber failed, ret:%{public}d", ret); return ret; } sensorManager_.StartDataReportThread(); if (!sensorManager_.SetBestSensorParams(sensorId, samplingPeriodNs, maxReportDelayNs)) { - SEN_HILOGE("SetBestSensorParams is failed"); + SEN_HILOGE("SetBestSensorParams failed"); clientInfo_.RemoveSubscriber(sensorId, pid); return ENABLE_SENSOR_ERR; } - return ret; + return ERR_OK; } -ErrCode SensorSuspendPolicy::GetActiveInfoList(int32_t pid, std::vector &activeInfoList) +void SensorSuspendPolicy::GetActiveInfoList(int32_t pid, std::vector &activeInfoList) { CALL_LOG_ENTER; std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); @@ -198,7 +185,6 @@ ErrCode SensorSuspendPolicy::GetActiveInfoList(int32_t pid, std::vector Date: Tue, 7 Mar 2023 09:13:02 +0000 Subject: [PATCH 13/53] update Signed-off-by: hui1975 Change-Id: Ief146fa069128593f8f96eadbb3f0663efd29273 --- services/sensor/BUILD.gn | 2 +- ...suspend_policy.h => sensor_power_policy.h} | 8 ++++---- services/sensor/include/sensor_service.h | 4 ++-- ...end_policy.cpp => sensor_power_policy.cpp} | 20 +++++++++---------- services/sensor/src/sensor_service.cpp | 8 ++++---- 5 files changed, 21 insertions(+), 21 deletions(-) rename services/sensor/include/{sensor_suspend_policy.h => sensor_power_policy.h} (92%) rename services/sensor/src/{sensor_suspend_policy.cpp => sensor_power_policy.cpp} (91%) diff --git a/services/sensor/BUILD.gn b/services/sensor/BUILD.gn index 24c33870..63762c03 100644 --- a/services/sensor/BUILD.gn +++ b/services/sensor/BUILD.gn @@ -27,10 +27,10 @@ ohos_shared_library("libsensor_service") { "src/sensor_data_processer.cpp", "src/sensor_dump.cpp", "src/sensor_manager.cpp", + "src/sensor_power_policy.cpp", "src/sensor_service.cpp", "src/sensor_service_stub.cpp", "src/stream_server.cpp", - "src/sensor_suspend_policy.cpp", ] include_dirs = [ diff --git a/services/sensor/include/sensor_suspend_policy.h b/services/sensor/include/sensor_power_policy.h similarity index 92% rename from services/sensor/include/sensor_suspend_policy.h rename to services/sensor/include/sensor_power_policy.h index 23090724..7433ecee 100644 --- a/services/sensor/include/sensor_suspend_policy.h +++ b/services/sensor/include/sensor_power_policy.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef SENSOR_SUSPEND_POLICY_H -#define SENSOR_SUSPEND_POLICY_H +#ifndef SENSOR_POWER_POLICY_H +#define SENSOR_POWER_POLICY_H #include #include @@ -31,7 +31,7 @@ namespace OHOS { namespace Sensors { -class SensorSuspendPolicy : public Singleton{ +class SensorPowerPolicy : public Singleton{ public: ErrCode SuspendSensors(int32_t pid); ErrCode ResumeSensors(int32_t pid); @@ -52,4 +52,4 @@ private: }; } // namespace Sensors } // namespace OHOS -#endif // SENSOR_SUSPEND_POLICY_H \ No newline at end of file +#endif // SENSOR_POWER_POLICY_H \ No newline at end of file diff --git a/services/sensor/include/sensor_service.h b/services/sensor/include/sensor_service.h index 162ef878..5a8dfbf6 100644 --- a/services/sensor/include/sensor_service.h +++ b/services/sensor/include/sensor_service.h @@ -28,8 +28,8 @@ #include "sensor_data_event.h" #include "sensor_hdi_connection.h" #include "sensor_manager.h" +#include "sensor_power_policy.h" #include "sensor_service_stub.h" -#include "sensor_suspend_policy.h" #include "stream_server.h" namespace OHOS { @@ -85,7 +85,7 @@ private: ClientInfo &clientInfo_ = ClientInfo::GetInstance(); SensorManager &sensorManager_ = SensorManager::GetInstance(); FlushInfoRecord &flushInfo_ = FlushInfoRecord::GetInstance(); - SensorSuspendPolicy &suspendPolicy_ = SensorSuspendPolicy::GetInstance(); + SensorPowerPolicy &sensorPowerPolicy_ = SensorPowerPolicy::GetInstance(); sptr sensorDataProcesser_ = nullptr; sptr reportDataCallback_ = nullptr; std::mutex uidLock_; diff --git a/services/sensor/src/sensor_suspend_policy.cpp b/services/sensor/src/sensor_power_policy.cpp similarity index 91% rename from services/sensor/src/sensor_suspend_policy.cpp rename to services/sensor/src/sensor_power_policy.cpp index 33b729e1..9899efce 100644 --- a/services/sensor/src/sensor_suspend_policy.cpp +++ b/services/sensor/src/sensor_power_policy.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "sensor_suspend_policy.h" +#include "sensor_power_policy.h" #include "sensor.h" #include "sensor_agent_type.h" @@ -23,17 +23,17 @@ namespace Sensors { using namespace OHOS::HiviewDFX; namespace { -constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SensorSuspendPolicy" }; +constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SensorPowerPolicy" }; constexpr int32_t INVALID_SENSOR_ID = -1; constexpr int64_t MAX_EVENT_COUNT = 1000; } // namespace -bool SensorSuspendPolicy::CheckFreezingSensor(int32_t sensorId) +bool SensorPowerPolicy::CheckFreezingSensor(int32_t sensorId) { return ((sensorId == SENSOR_TYPE_ID_PEDOMETER_DETECTION) || (sensorId == SENSOR_TYPE_ID_PEDOMETER)); } -ErrCode SensorSuspendPolicy::SuspendSensors(int32_t pid) +ErrCode SensorPowerPolicy::SuspendSensors(int32_t pid) { CALL_LOG_ENTER; std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); @@ -67,7 +67,7 @@ ErrCode SensorSuspendPolicy::SuspendSensors(int32_t pid) return ERR_OK; } -bool SensorSuspendPolicy::Suspend(std::unordered_map &SensorInfoMap, +bool SensorPowerPolicy::Suspend(std::unordered_map &SensorInfoMap, std::vector &sensorIdList, int32_t pid) { CALL_LOG_ENTER; @@ -94,7 +94,7 @@ bool SensorSuspendPolicy::Suspend(std::unordered_map & return isAllSuspend; } -ErrCode SensorSuspendPolicy::ResumeSensors(int32_t pid) +ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) { CALL_LOG_ENTER; std::lock_guard pidSensorInfoLock(pidSensorInfoMutex_); @@ -125,7 +125,7 @@ ErrCode SensorSuspendPolicy::ResumeSensors(int32_t pid) return ERR_OK; } -bool SensorSuspendPolicy::Resume(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, +bool SensorPowerPolicy::Resume(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) { CALL_LOG_ENTER; @@ -157,7 +157,7 @@ bool SensorSuspendPolicy::Resume(int32_t pid, int32_t sensorId, int64_t sampling return true; } -ErrCode SensorSuspendPolicy::RestoreSensorInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, +ErrCode SensorPowerPolicy::RestoreSensorInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) { CALL_LOG_ENTER; @@ -175,7 +175,7 @@ ErrCode SensorSuspendPolicy::RestoreSensorInfo(int32_t pid, int32_t sensorId, in return ERR_OK; } -void SensorSuspendPolicy::GetActiveInfoList(int32_t pid, std::vector &activeInfoList) +void SensorPowerPolicy::GetActiveInfoList(int32_t pid, std::vector &activeInfoList) { CALL_LOG_ENTER; std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); @@ -187,7 +187,7 @@ void SensorSuspendPolicy::GetActiveInfoList(int32_t pid, std::vector } } -void SensorSuspendPolicy::ReportActiveInfo(ActiveInfo activeInfo, +void SensorPowerPolicy::ReportActiveInfo(ActiveInfo activeInfo, const std::vector &sessionList) { CALL_LOG_ENTER; diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index b7e04dee..e3c05ca8 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -430,7 +430,7 @@ ErrCode SensorService::SuspendSensors(int32_t pid) SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } - return suspendPolicy_.SuspendSensors(pid); + return sensorPowerPolicy_.SuspendSensors(pid); } ErrCode SensorService::ResumeSensors(int32_t pid) @@ -440,7 +440,7 @@ ErrCode SensorService::ResumeSensors(int32_t pid) SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } - return suspendPolicy_.ResumeSensors(pid); + return sensorPowerPolicy_.ResumeSensors(pid); } ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector &activeInfoList) @@ -450,7 +450,7 @@ ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector &a SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } - suspendPolicy_.GetActiveInfoList(pid, activeInfoList); + sensorPowerPolicy_.GetActiveInfoList(pid, activeInfoList); return ERR_OK; } @@ -510,7 +510,7 @@ void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid) SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); ActiveInfo activeInfo(pid, sensorId, sensorInfo.GetSamplingPeriodNs(), sensorInfo.GetMaxReportDelayNs()); - suspendPolicy_.ReportActiveInfo(activeInfo, sessionList); + sensorPowerPolicy_.ReportActiveInfo(activeInfo, sessionList); } } // namespace Sensors } // namespace OHOS -- Gitee From 59d4d1b1d7e6610f2b84cbdffadd329ca711ba58 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Wed, 8 Mar 2023 01:18:17 +0000 Subject: [PATCH 14/53] update Signed-off-by: hui1975 Change-Id: I86e4744aa668a652aa52f0ed0b503e96f4dfa8c7 --- frameworks/native/sensor/src/sensor_data_channel.cpp | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/frameworks/native/sensor/src/sensor_data_channel.cpp b/frameworks/native/sensor/src/sensor_data_channel.cpp index 27e4e058..7dd29d6d 100644 --- a/frameworks/native/sensor/src/sensor_data_channel.cpp +++ b/frameworks/native/sensor/src/sensor_data_channel.cpp @@ -80,18 +80,8 @@ int32_t SensorDataChannel::InnerSensorDataChannel() int32_t SensorDataChannel::DestroySensorDataChannel() { - std::lock_guard eventRunnerLock(eventRunnerMutex_); - CHKPL(eventHandler_); int32_t receiveFd = GetReceiveDataFd(); - eventHandler_->RemoveFileDescriptorListener(receiveFd); - auto it = listenedFdSet_.find(receiveFd); - if (it != listenedFdSet_.end()) { - listenedFdSet_.erase(it); - } - if (listenedFdSet_.empty() && eventHandler_ != nullptr) { - eventHandler_ = nullptr; - SEN_HILOGD("Set eventHandler_ nullptr"); - } + DelFdListener(receiveFd); return DestroySensorBasicChannel(); } -- Gitee From 3a6e5566c1272393721801ca31637ae493bcdcc4 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Wed, 8 Mar 2023 01:53:13 +0000 Subject: [PATCH 15/53] =?UTF-8?q?=E8=B0=83=E6=95=B4=E5=A4=B4=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E9=A1=BA=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: I2e0c5e8d8979ea99df39783cb372fcfa29eed2ec --- utils/ipc/include/stream_session.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/ipc/include/stream_session.h b/utils/ipc/include/stream_session.h index adbf4dc1..eba3fb1a 100644 --- a/utils/ipc/include/stream_session.h +++ b/utils/ipc/include/stream_session.h @@ -17,8 +17,8 @@ #define STREAM_SESSION_H #include -#include #include +#include #include #include -- Gitee From b3917ccee2941dd40aae2b43db835a2758aa5295 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Wed, 8 Mar 2023 02:43:59 +0000 Subject: [PATCH 16/53] =?UTF-8?q?=E6=81=A2=E5=A4=8Dsocket=E7=9A=84?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: I2b91d22f616dfdaf419dfb4ac313ec62fcc22495 --- utils/ipc/src/circle_stream_buffer.cpp | 2 +- utils/ipc/src/net_packet.cpp | 11 +++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/utils/ipc/src/circle_stream_buffer.cpp b/utils/ipc/src/circle_stream_buffer.cpp index 1f1845b2..a2c91f54 100644 --- a/utils/ipc/src/circle_stream_buffer.cpp +++ b/utils/ipc/src/circle_stream_buffer.cpp @@ -44,7 +44,7 @@ bool CircleStreamBuffer::Write(const char *buf, size_t size) void CircleStreamBuffer::CopyDataToBegin() { int32_t unreadSize = UnreadSize(); - if (unreadSize > 0 && rPos_ > 0 && sizeof(szBuff_) > wPos_) { + if (unreadSize > 0 && rPos_ > 0) { int32_t pos = 0; for (int32_t i = rPos_; i <= wPos_;) { szBuff_[pos++] = szBuff_[i++]; diff --git a/utils/ipc/src/net_packet.cpp b/utils/ipc/src/net_packet.cpp index 00acc027..7e3a3bae 100644 --- a/utils/ipc/src/net_packet.cpp +++ b/utils/ipc/src/net_packet.cpp @@ -32,12 +32,11 @@ void NetPacket::MakeData(StreamBuffer &buf) const { PACKHEAD head = {msgId_, wPos_}; buf << head; - if (wPos_ < 0) { - return; - } - if (!buf.Write(&szBuff_[0], wPos_)) { - SEN_HILOGE("Write data to stream failed, errCode:%{public}d", PROTO_STREAM_BUF_WRITE_FAIL); - return; + if (wPos_ > 0) { + if (!buf.Write(&szBuff_[0], wPos_)) { + SEN_HILOGE("Write data to stream failed, errCode:%{public}d", PROTO_STREAM_BUF_WRITE_FAIL); + return; + } } } -- Gitee From 6e865adfe28fea1ab29224a475242fabc544eff6 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Thu, 9 Mar 2023 09:36:25 +0000 Subject: [PATCH 17/53] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hui1975 Change-Id: Ied81bdda796b6ac10c61588da7d6d8fa11a492a6 --- frameworks/native/sensor/src/fd_listener.cpp | 8 +- .../sensor/src/sensor_service_client.cpp | 2 +- .../test/unittest/sensor_power_test.cpp | 128 +++--------------- services/sensor/src/sensor_service.cpp | 2 +- services/sensor/src/stream_server.cpp | 8 +- utils/common/include/active_info.h | 2 +- utils/common/src/active_info.cpp | 3 +- utils/ipc/include/circle_stream_buffer.h | 4 +- utils/ipc/include/net_packet.h | 2 +- utils/ipc/include/proto.h | 23 ++-- utils/ipc/include/stream_buffer.h | 42 +++--- utils/ipc/src/circle_stream_buffer.cpp | 21 ++- utils/ipc/src/net_packet.cpp | 9 +- utils/ipc/src/stream_buffer.cpp | 47 ++++--- utils/ipc/src/stream_session.cpp | 25 ++-- utils/ipc/src/stream_socket.cpp | 22 +-- 16 files changed, 125 insertions(+), 223 deletions(-) diff --git a/frameworks/native/sensor/src/fd_listener.cpp b/frameworks/native/sensor/src/fd_listener.cpp index cba25a92..527ccaed 100644 --- a/frameworks/native/sensor/src/fd_listener.cpp +++ b/frameworks/native/sensor/src/fd_listener.cpp @@ -38,9 +38,9 @@ void FdListener::OnReadable(int32_t fd) SEN_HILOGE("Invalid fd"); return; } - char szBuf[PROTO_MAX_PACKET_BUF_SIZE] = {}; - for (int32_t i = 0; i < PROTO_MAX_RECV_LIMIT; i++) { - ssize_t size = recv(fd, szBuf, PROTO_MAX_PACKET_BUF_SIZE, MSG_DONTWAIT | MSG_NOSIGNAL); + char szBuf[MAX_PACKET_BUF_SIZE] = {}; + for (size_t i = 0; i < MAX_RECV_LIMIT; i++) { + ssize_t size = recv(fd, szBuf, MAX_PACKET_BUF_SIZE, MSG_DONTWAIT | MSG_NOSIGNAL); if (size > 0) { channel_->receiveMessage_(szBuf, size); } else if (size < 0) { @@ -56,7 +56,7 @@ void FdListener::OnReadable(int32_t fd) i, errno); break; } - if (size < PROTO_MAX_PACKET_BUF_SIZE) { + if (size < MAX_PACKET_BUF_SIZE) { break; } } diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index e4240993..910032b6 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -333,7 +333,7 @@ int32_t SensorServiceClient::UnregisterSensorActiveInfoCB(SensorActiveInfoCB cal void SensorServiceClient::ReceiveMessage(const char *buf, size_t size) { CHKPV(buf); - if (size == 0 || size > PROTO_MAX_PACKET_BUF_SIZE) { + if (size == 0 || size > MAX_PACKET_BUF_SIZE) { SEN_HILOGE("Invalid input param size. size:%{public}zu", size); return; } diff --git a/interfaces/native/test/unittest/sensor_power_test.cpp b/interfaces/native/test/unittest/sensor_power_test.cpp index f37c3402..d7816721 100644 --- a/interfaces/native/test/unittest/sensor_power_test.cpp +++ b/interfaces/native/test/unittest/sensor_power_test.cpp @@ -151,37 +151,26 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_005, TestSize.Level1) HWTEST_F(SensorPowerTest, SensorPowerTest_006, TestSize.Level1) { - // 场景用例1,订阅ACC传感器》查询传感器订阅数据》休眠进程的传感器》恢复进程的传感器》取消订阅ACC传感器 + // 场景用例1,订阅并打开ACC传感器》休眠进程的传感器》恢复进程的传感器》关闭并取消订阅ACC传感器 SEN_HILOGI("SensorPowerTest_006 in"); SensorUser user; user.callback = SensorDataCallbackImpl; int32_t ret = SubscribeSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = SetBatch(sensorId, &user, 100000000, 100000000); + ret = SetBatch(sensorId, &user, 100000000, 0); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); ret = ActivateSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); std::this_thread::sleep_for(std::chrono::milliseconds(500)); - SensorActiveInfo *sensorActiveInfos {nullptr}; - int32_t count { 0 }; - ret = GetSensorActiveInfos(process_pid, &sensorActiveInfos, &count); - for (int32_t i = 0; i < count; ++i) { - SensorActiveInfo *curSensorActiveInfo = sensorActiveInfos + i; - SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, samplingPeriodNs:%{public}" PRId64 ", " - "maxReportDelayNs:%{public}" PRId64 "", curSensorActiveInfo->pid, curSensorActiveInfo->sensorId, - curSensorActiveInfo->samplingPeriodNs, curSensorActiveInfo->maxReportDelayNs); - } - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = SuspendSensors(process_pid); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); ret = ResumeSensors(process_pid); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); ret = DeactivateSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); @@ -191,23 +180,19 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_006, TestSize.Level1) HWTEST_F(SensorPowerTest, SensorPowerTest_007, TestSize.Level1) { - // 场景用例2,订阅ACC传感器》休眠进程的传感器》查询传感器订阅数据》恢复进程的传感器》取消订阅ACC传感器 + // 场景用例2,订阅并打开ACC传感器》查询传感器打开数据》休眠进程的传感器》恢复进程的传感器》关闭并取消订阅ACC传感器 SEN_HILOGI("SensorPowerTest_007 in"); SensorUser user; user.callback = SensorDataCallbackImpl; int32_t ret = SubscribeSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = SetBatch(sensorId, &user, 100000000, 100000000); + ret = SetBatch(sensorId, &user, 100000000, 0); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); ret = ActivateSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); std::this_thread::sleep_for(std::chrono::milliseconds(500)); - ret = SuspendSensors(process_pid); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); - SensorActiveInfo *sensorActiveInfos {nullptr}; int32_t count { 0 }; ret = GetSensorActiveInfos(process_pid, &sensorActiveInfos, &count); @@ -219,49 +204,13 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_007, TestSize.Level1) } ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = ResumeSensors(process_pid); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(1000)); - - ret = DeactivateSensor(sensorId, &user); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = UnsubscribeSensor(sensorId, &user); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); -} - -HWTEST_F(SensorPowerTest, SensorPowerTest_008, TestSize.Level1) -{ - // 场景用例3,订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》查询传感器订阅数据》取消订阅ACC传感器 - SEN_HILOGI("SensorPowerTest_008 in"); - SensorUser user; - user.callback = SensorDataCallbackImpl; - - int32_t ret = SubscribeSensor(sensorId, &user); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = SetBatch(sensorId, &user, 100000000, 100000000); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = ActivateSensor(sensorId, &user); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - ret = SuspendSensors(process_pid); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); - - ret = ResumeSensors(process_pid); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); - SensorActiveInfo *sensorActiveInfos {nullptr}; - int32_t count { 0 }; - ret = GetSensorActiveInfos(process_pid, &sensorActiveInfos, &count); - for (int32_t i = 0; i < count; ++i) { - SensorActiveInfo *curSensorActiveInfo = sensorActiveInfos + i; - SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, samplingPeriodNs:%{public}" PRId64 ", " - "maxReportDelayNs:%{public}" PRId64 "", curSensorActiveInfo->pid, curSensorActiveInfo->sensorId, - curSensorActiveInfo->samplingPeriodNs, curSensorActiveInfo->maxReportDelayNs); - } + ret = ResumeSensors(process_pid); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); ret = DeactivateSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); @@ -269,10 +218,10 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_008, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, SensorPowerTest_009, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_008, TestSize.Level1) { - // 场景用例4,注册回调函数》订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》取消订阅ACC传感器》取消注册回调函数 - SEN_HILOGI("SensorPowerTest_009 in"); + // 场景用例3,注册回调函数》订阅并打开ACC传感器》休眠进程的传感器》恢复进程的传感器》关闭并取消订阅ACC传感器》取消注册回调函数 + SEN_HILOGI("SensorPowerTest_008 in"); SensorUser user; user.callback = SensorDataCallbackImpl; SensorActiveInfoCB callback = SensorActiveInfoCBImpl; @@ -282,7 +231,7 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_009, TestSize.Level1) ret = SubscribeSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = SetBatch(sensorId, &user, 100000000, 100000000); + ret = SetBatch(sensorId, &user, 100000000, 0); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); ret = ActivateSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); @@ -290,11 +239,11 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_009, TestSize.Level1) ret = SuspendSensors(process_pid); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); ret = ResumeSensors(process_pid); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); ret = DeactivateSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); @@ -305,47 +254,10 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_009, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); } -HWTEST_F(SensorPowerTest, SensorPowerTest_010, TestSize.Level1) -{ - // 场景用例5,注册回调函数》订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》取消注册回调函数》取消订阅ACC传感器 - SEN_HILOGI("SensorPowerTest_010 in"); - SensorUser user; - user.callback = SensorDataCallbackImpl; - SensorActiveInfoCB callback = SensorActiveInfoCBImpl; - - int32_t ret = RegisterSensorActiveInfoCB(callback); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - - ret = SubscribeSensor(sensorId, &user); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = SetBatch(sensorId, &user, 100000000, 100000000); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = ActivateSensor(sensorId, &user); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - - ret = SuspendSensors(process_pid); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); - - ret = ResumeSensors(process_pid); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(1000)); - - ret = DeactivateSensor(sensorId, &user); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - - ret = UnregisterSensorActiveInfoCB(callback); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - - ret = UnsubscribeSensor(sensorId, &user); - ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); -} - -HWTEST_F(SensorPowerTest, SensorPowerTest_011, TestSize.Level1) +HWTEST_F(SensorPowerTest, SensorPowerTest_009, TestSize.Level1) { - // 场景用例6,注册回调函数1》注册回调函数2》订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》取消订阅ACC传感器》取消注册回调函数1》取消注册回调函数2 - SEN_HILOGI("SensorPowerTest_011 in"); + // 场景用例4,注册回调函数1》注册回调函数2》订阅ACC传感器》休眠进程的传感器》恢复进程的传感器》取消订阅ACC传感器》取消注册回调函数1》取消注册回调函数2 + SEN_HILOGI("SensorPowerTest_009 in"); SensorUser user; user.callback = SensorDataCallbackImpl; SensorActiveInfoCB callback = SensorActiveInfoCBImpl; @@ -358,7 +270,7 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_011, TestSize.Level1) ret = SubscribeSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = SetBatch(sensorId, &user, 100000000, 100000000); + ret = SetBatch(sensorId, &user, 100000000, 0); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); ret = ActivateSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); @@ -366,11 +278,11 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_011, TestSize.Level1) ret = SuspendSensors(process_pid); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); ret = ResumeSensors(process_pid); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); ret = DeactivateSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index e3c05ca8..d9e135dc 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -390,7 +390,7 @@ void SensorService::UnregisterClientDeathRecipient(sptr sensorCli return; } if (!clientInfo_.IsUnregisterClientDeathRecipient(pid)) { - SEN_HILOGD("Client call other service, not need unregister client death recipient"); + SEN_HILOGD("Client call other service, can not unregister client death recipient"); return; } sptr client = iface_cast(sensorClient); diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index 31399c25..6d50583e 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -49,7 +49,7 @@ bool StreamServer::SendMsg(int32_t fd, NetPacket& pkt) } auto ses = GetSession(fd); if (ses == nullptr) { - SEN_HILOGE("Fd not found, The message was discarded. errCode:%{public}d", PROTO_SESSION_NOT_FOUND); + SEN_HILOGE("Fd not found, The message was discarded."); return false; } return ses->SendMsg(pkt); @@ -155,7 +155,7 @@ int32_t StreamServer::AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenT sess = std::make_shared(programName, moduleType, serverFd, uid, pid); sess->SetTokenType(tokenType); if (!AddSession(sess)) { - SEN_HILOGE("AddSession fail errCode:%{public}d", PROTO_ADD_SESSION_FAIL); + SEN_HILOGE("AddSession fail"); goto CLOSE_SOCK; } return ERR_OK; @@ -182,9 +182,9 @@ bool StreamServer::AddSession(SessionPtr ses) SEN_HILOGE("Get process failed"); return false; } - if (sessionsMap_.size() > PROTO_MAX_SESSON_ALARM) { + if (sessionsMap_.size() > MAX_SESSON_ALARM) { SEN_HILOGE("Too many clients. Warning Value:%{public}d, Current Value:%{public}zd", - PROTO_MAX_SESSON_ALARM, sessionsMap_.size()); + MAX_SESSON_ALARM, sessionsMap_.size()); return false; } DelSession(pid); diff --git a/utils/common/include/active_info.h b/utils/common/include/active_info.h index f068912a..721e96c4 100644 --- a/utils/common/include/active_info.h +++ b/utils/common/include/active_info.h @@ -24,7 +24,7 @@ class ActiveInfo : public Parcelable { public: ActiveInfo() = default; ActiveInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); - virtual ~ActiveInfo() = default; + ~ActiveInfo() = default; int32_t GetPid() const; void SetPid(int32_t pid); int32_t GetSensorId() const; diff --git a/utils/common/src/active_info.cpp b/utils/common/src/active_info.cpp index 270b479d..6e2f836e 100644 --- a/utils/common/src/active_info.cpp +++ b/utils/common/src/active_info.cpp @@ -25,7 +25,8 @@ constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "ActiveInfo" }; } ActiveInfo::ActiveInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) - :pid_(pid), sensorId_(sensorId), samplingPeriodNs_(samplingPeriodNs), maxReportDelayNs_(maxReportDelayNs) {}; + :pid_(pid), sensorId_(sensorId), samplingPeriodNs_(samplingPeriodNs), maxReportDelayNs_(maxReportDelayNs) +{} int32_t ActiveInfo::GetPid() const { diff --git a/utils/ipc/include/circle_stream_buffer.h b/utils/ipc/include/circle_stream_buffer.h index 3aaea490..569ab5b1 100644 --- a/utils/ipc/include/circle_stream_buffer.h +++ b/utils/ipc/include/circle_stream_buffer.h @@ -24,9 +24,9 @@ class CircleStreamBuffer : public StreamBuffer { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "CircleStreamBuffer" }; public: CircleStreamBuffer() = default; - virtual ~CircleStreamBuffer() = default; + ~CircleStreamBuffer() = default; bool CheckWrite(size_t size); - virtual bool Write(const char *buf, size_t size) override; + bool Write(const char *buf, size_t size) override; DISALLOW_MOVE(CircleStreamBuffer); protected: diff --git a/utils/ipc/include/net_packet.h b/utils/ipc/include/net_packet.h index 33d3545e..c88d1099 100644 --- a/utils/ipc/include/net_packet.h +++ b/utils/ipc/include/net_packet.h @@ -37,7 +37,7 @@ public: virtual ~NetPacket(); virtual void MakeData(StreamBuffer &buf) const; size_t GetSize() const; - int32_t GetPacketLength() const; + size_t GetPacketLength() const; const char* GetData() const; MessageId GetMsgId() const; DISALLOW_MOVE(NetPacket); diff --git a/utils/ipc/include/proto.h b/utils/ipc/include/proto.h index 5b074be4..d0250198 100644 --- a/utils/ipc/include/proto.h +++ b/utils/ipc/include/proto.h @@ -20,23 +20,16 @@ namespace OHOS { namespace Sensors { -#define PROTO_SEND_RETRY_LIMIT 32 -#define PROTO_SEND_RETRY_SLEEP_TIME 10000 +#define SEND_RETRY_LIMIT 32 +#define SEND_RETRY_SLEEP_TIME 10000 -static const int32_t PROTO_STREAM_BUF_READ_FAIL = 1; -static const int32_t PROTO_STREAM_BUF_WRITE_FAIL = 2; -static const int32_t PROTO_MEM_OUT_OF_BOUNDS = 3; -static const int32_t PROTO_MEMCPY_SEC_FUN_FAIL = 4; -static const int32_t PROTO_PARAM_INPUT_INVALID = 5; -static const int32_t PROTO_SESSION_NOT_FOUND = 8; -static const int32_t PROTO_MAX_VECTOR_SIZE = 10; -static const int32_t PROTO_ADD_SESSION_FAIL = 11; -static const int32_t PROTO_MAX_SESSON_ALARM = 12; -static const int32_t PROTO_MAX_RECV_LIMIT = 13; -static const int32_t PROTO_MAX_STREAM_BUF_SIZE = 256; -static const int32_t PROTO_MAX_PACKET_BUF_SIZE = 256; -static const int32_t PROTO_ONCE_PROCESS_NETPACKET_LIMIT = 100; +static const size_t MAX_VECTOR_SIZE = 10; +static const size_t MAX_SESSON_ALARM = 100; +static const size_t MAX_RECV_LIMIT = 13; +static const size_t MAX_STREAM_BUF_SIZE = 256; +static const size_t MAX_PACKET_BUF_SIZE = 256; +static const size_t ONCE_PROCESS_NETPACKET_LIMIT = 100; enum class MessageId : int32_t { INVALID, diff --git a/utils/ipc/include/stream_buffer.h b/utils/ipc/include/stream_buffer.h index 0cea6fae..6e376b0c 100644 --- a/utils/ipc/include/stream_buffer.h +++ b/utils/ipc/include/stream_buffer.h @@ -37,7 +37,7 @@ public: virtual ~StreamBuffer() = default; void Reset(); void Clean(); - bool SeekReadPos(int32_t n); + bool SeekReadPos(size_t n); bool Read(std::string &buf); bool Read(StreamBuffer &buf); bool Read(char *buf, size_t size); @@ -47,8 +47,8 @@ public: bool IsEmpty() const; bool ChkRWError() const; size_t Size() const; - int32_t UnreadSize() const; - int32_t GetAvailableBufSize() const; + size_t UnreadSize() const; + size_t GetAvailableBufSize() const; const std::string& GetErrorStatusRemark() const; const char* Data() const; @@ -76,19 +76,19 @@ protected: ERROR_STATUS_WRITE, }; ErrorStatus rwErrorStatus_ = ErrorStatus::ERROR_STATUS_OK; - int32_t rCount_ { 0 }; - int32_t wCount_ { 0 }; - int32_t rPos_ { 0 }; - int32_t wPos_ { 0 }; - char szBuff_[PROTO_MAX_STREAM_BUF_SIZE + 1] = {}; + size_t rCount_ { 0 }; + size_t wCount_ { 0 }; + size_t rPos_ { 0 }; + size_t wPos_ { 0 }; + char szBuff_[MAX_STREAM_BUF_SIZE + 1] = {}; }; template bool StreamBuffer::Read(T &data) { if (!Read(reinterpret_cast(&data), sizeof(data))) { - SEN_HILOGE("[%{public}s] size:%{public}zu count:%{public}d,errCode:%{public}d", - GetErrorStatusRemark().c_str(), sizeof(data), rCount_ + 1, PROTO_STREAM_BUF_READ_FAIL); + SEN_HILOGE("%{public}s, size:%{public}zu, count:%{public}zu", + GetErrorStatusRemark().c_str(), sizeof(data), rCount_ + 1); return false; } return true; @@ -98,8 +98,8 @@ template bool StreamBuffer::Write(const T &data) { if (!Write(reinterpret_cast(&data), sizeof(data))) { - SEN_HILOGE("[%{public}s] size:%{public}zu,count:%{public}d,errCode:%{public}d", - GetErrorStatusRemark().c_str(), sizeof(data), wCount_ + 1, PROTO_STREAM_BUF_WRITE_FAIL); + SEN_HILOGE("%{public}s, size:%{public}zu, count:%{public}zu", + GetErrorStatusRemark().c_str(), sizeof(data), wCount_ + 1); return false; } return true; @@ -108,19 +108,19 @@ bool StreamBuffer::Write(const T &data) template bool StreamBuffer::Read(std::vector &data) { - int32_t size = 0; + size_t size = 0; if (!Read(size)) { - SEN_HILOGE("Read vector size error"); + SEN_HILOGE("Read vector size failed"); return false; } - if (size < 0 || size > PROTO_MAX_VECTOR_SIZE) { - SEN_HILOGE("Read vector size:%{public}d error", size); + if (size > MAX_VECTOR_SIZE) { + SEN_HILOGE("Vector size is invalid, size:%{public}zu", size); return false; } - for (int32_t i = 0; i < size; i++) { + for (size_t i = 0; i < size; i++) { T val; if (!Read(val)) { - SEN_HILOGE("Read vector data error"); + SEN_HILOGE("Read vector data failed"); return false; } data.push_back(val); @@ -135,14 +135,14 @@ bool StreamBuffer::Write(const std::vector &data) SEN_HILOGE("Vector exceeds the max range"); return false; } - int32_t size = static_cast(data.size()); + size_t size = data.size(); if (!Write(size)) { - SEN_HILOGE("Write vector size error"); + SEN_HILOGE("Write vector size failed"); return false; } for (const auto &item : data) { if (!Write(item)) { - SEN_HILOGE("Write vector data error"); + SEN_HILOGE("Write vector data failed"); return false; } } diff --git a/utils/ipc/src/circle_stream_buffer.cpp b/utils/ipc/src/circle_stream_buffer.cpp index a2c91f54..11bb9409 100644 --- a/utils/ipc/src/circle_stream_buffer.cpp +++ b/utils/ipc/src/circle_stream_buffer.cpp @@ -21,21 +21,20 @@ namespace OHOS { namespace Sensors { bool CircleStreamBuffer::CheckWrite(size_t size) { - int32_t bufferSize = static_cast(size); - int32_t availSize = GetAvailableBufSize(); - if (bufferSize > availSize && rPos_ > 0) { + size_t availSize = GetAvailableBufSize(); + if (size > availSize && rPos_ > 0) { CopyDataToBegin(); availSize = GetAvailableBufSize(); } - return (availSize >= bufferSize); + return (availSize >= size); } bool CircleStreamBuffer::Write(const char *buf, size_t size) { if (!CheckWrite(size)) { - SEN_HILOGE("Out of buffer memory, availableSize:%{public}d, size:%{public}zu," - "unreadSize:%{public}d, rPos:%{public}d, wPos:%{public}d", - GetAvailableBufSize(), size, UnreadSize(), rPos_, wPos_); + SEN_HILOGE("Out of buffer memory, availableSize:%{public}zu, size:%{public}zu," + "unreadSize:%{public}zu, rPos:%{public}zu, wPos:%{public}zu", + GetAvailableBufSize(), size, UnreadSize(), rPos_, wPos_); return false; } return StreamBuffer::Write(buf, size); @@ -43,14 +42,14 @@ bool CircleStreamBuffer::Write(const char *buf, size_t size) void CircleStreamBuffer::CopyDataToBegin() { - int32_t unreadSize = UnreadSize(); + size_t unreadSize = UnreadSize(); if (unreadSize > 0 && rPos_ > 0) { - int32_t pos = 0; - for (int32_t i = rPos_; i <= wPos_;) { + size_t pos = 0; + for (size_t i = rPos_; i <= wPos_;) { szBuff_[pos++] = szBuff_[i++]; } } - SEN_HILOGD("UnreadSize:%{public}d, rPos:%{public}d, wPos:%{public}d", unreadSize, rPos_, wPos_); + SEN_HILOGD("UnreadSize:%{public}zu, rPos:%{public}zu, wPos:%{public}zu", unreadSize, rPos_, wPos_); rPos_ = 0; wPos_ = unreadSize; } diff --git a/utils/ipc/src/net_packet.cpp b/utils/ipc/src/net_packet.cpp index 7e3a3bae..6a0b62fe 100644 --- a/utils/ipc/src/net_packet.cpp +++ b/utils/ipc/src/net_packet.cpp @@ -19,7 +19,8 @@ namespace OHOS { namespace Sensors { -NetPacket::NetPacket(MessageId msgId) : msgId_(msgId) {} +NetPacket::NetPacket(MessageId msgId) : msgId_(msgId) +{} NetPacket::NetPacket(const NetPacket &pkt) : NetPacket(pkt.GetMsgId()) { @@ -34,7 +35,7 @@ void NetPacket::MakeData(StreamBuffer &buf) const buf << head; if (wPos_ > 0) { if (!buf.Write(&szBuff_[0], wPos_)) { - SEN_HILOGE("Write data to stream failed, errCode:%{public}d", PROTO_STREAM_BUF_WRITE_FAIL); + SEN_HILOGE("Write data to stream failed"); return; } } @@ -45,9 +46,9 @@ size_t NetPacket::GetSize() const return Size(); } -int32_t NetPacket::GetPacketLength() const +size_t NetPacket::GetPacketLength() const { - return (static_cast(sizeof(PackHead)) + wPos_); + return sizeof(PackHead) + wPos_; } const char* NetPacket::GetData() const diff --git a/utils/ipc/src/stream_buffer.cpp b/utils/ipc/src/stream_buffer.cpp index 04929262..53764b97 100644 --- a/utils/ipc/src/stream_buffer.cpp +++ b/utils/ipc/src/stream_buffer.cpp @@ -50,11 +50,11 @@ void StreamBuffer::Clean() } } -bool StreamBuffer::SeekReadPos(int32_t n) +bool StreamBuffer::SeekReadPos(size_t n) { - int32_t pos = rPos_ + n; - if (pos < 0 || pos > wPos_) { - SEN_HILOGE("The position in the calculation is not as expected. pos:%{public}d [0, %{public}d]", pos, wPos_); + size_t pos = rPos_ + n; + if (pos > wPos_) { + SEN_HILOGE("The position in the calculation is not as expected. pos:%{public}zu, [0, %{public}zu]", pos, wPos_); return false; } rPos_ = pos; @@ -64,12 +64,12 @@ bool StreamBuffer::SeekReadPos(int32_t n) bool StreamBuffer::Read(std::string &buf) { if (rPos_ == wPos_) { - SEN_HILOGE("Not enough memory to read, errCode:%{public}d", PROTO_STREAM_BUF_READ_FAIL); + SEN_HILOGE("Not enough memory to read"); rwErrorStatus_ = ErrorStatus::ERROR_STATUS_READ; return false; } buf = ReadBuf(); - rPos_ += static_cast(buf.length()) + 1; + rPos_ += buf.length() + 1; return (buf.length() > 0); } @@ -94,27 +94,27 @@ bool StreamBuffer::Read(char *buf, size_t size) return false; } if (buf == nullptr) { - SEN_HILOGE("Invalid input parameter buf=nullptr errCode:%{public}d", PROTO_PARAM_INPUT_INVALID); + SEN_HILOGE("Invalid input parameter, buf is nullptr"); rwErrorStatus_ = ErrorStatus::ERROR_STATUS_READ; return false; } if (size == 0) { - SEN_HILOGE("Invalid input parameter size=%{public}zu errCode:%{public}d", size, PROTO_PARAM_INPUT_INVALID); + SEN_HILOGE("Invalid input parameter, size:%{public}zu", size); rwErrorStatus_ = ErrorStatus::ERROR_STATUS_READ; return false; } - if (rPos_ + static_cast(size) > wPos_) { - SEN_HILOGE("Memory out of bounds on read... errCode:%{public}d", PROTO_MEM_OUT_OF_BOUNDS); + if (rPos_ + size > wPos_) { + SEN_HILOGE("Memory out of bounds on read"); rwErrorStatus_ = ErrorStatus::ERROR_STATUS_READ; return false; } errno_t ret = memcpy_sp(buf, size, ReadBuf(), size); if (ret != EOK) { - SEN_HILOGE("Failed to call memcpy_sp. errCode:%{public}d", PROTO_MEMCPY_SEC_FUN_FAIL); + SEN_HILOGE("Failed to call memcpy_sp"); rwErrorStatus_ = ErrorStatus::ERROR_STATUS_READ; return false; } - rPos_ += static_cast(size); + rPos_ += size; rCount_ += 1; return true; } @@ -125,28 +125,28 @@ bool StreamBuffer::Write(const char *buf, size_t size) return false; } if (buf == nullptr) { - SEN_HILOGE("Invalid input parameter buf=nullptr errCode:%{public}d", PROTO_PARAM_INPUT_INVALID); + SEN_HILOGE("Invalid input parameter, buf is nullptr"); rwErrorStatus_ = ErrorStatus::ERROR_STATUS_WRITE; return false; } if (size == 0) { - SEN_HILOGE("Invalid input parameter size=%{public}zu errCode:%{public}d", size, PROTO_PARAM_INPUT_INVALID); + SEN_HILOGE("Invalid input parameter, size:%{public}zu", size); rwErrorStatus_ = ErrorStatus::ERROR_STATUS_WRITE; return false; } - if (wPos_ + static_cast(size) > PROTO_MAX_STREAM_BUF_SIZE) { - SEN_HILOGE("The write length exceeds buffer. wIdx:%{public}d size:%{public}zu maxBufSize:%{public}d" - "errCode:%{public}d", wPos_, size, PROTO_MAX_STREAM_BUF_SIZE, PROTO_MEM_OUT_OF_BOUNDS); + if (wPos_ + size > MAX_STREAM_BUF_SIZE) { + SEN_HILOGE("The write length exceeds buffer. wPos:%{public}zu, size:%{public}zu, maxBufSize:%{public}zu", + wPos_, size, MAX_STREAM_BUF_SIZE); rwErrorStatus_ = ErrorStatus::ERROR_STATUS_WRITE; return false; } errno_t ret = memcpy_sp(&szBuff_[wPos_], GetAvailableBufSize(), buf, size); if (ret != EOK) { - SEN_HILOGE("Failed to call memcpy_sp. errCode:%{public}d", PROTO_MEMCPY_SEC_FUN_FAIL); + SEN_HILOGE("Failed to call memcpy_sp"); rwErrorStatus_ = ErrorStatus::ERROR_STATUS_WRITE; return false; } - wPos_ += static_cast(size); + wPos_ += size; wCount_ += 1; return true; } @@ -158,17 +158,17 @@ bool StreamBuffer::IsEmpty() const size_t StreamBuffer::Size() const { - return static_cast(wPos_); + return wPos_; } -int32_t StreamBuffer::UnreadSize() const +size_t StreamBuffer::UnreadSize() const { return ((wPos_ <= rPos_) ? 0 : (wPos_ - rPos_)); } -int32_t StreamBuffer::GetAvailableBufSize() const +size_t StreamBuffer::GetAvailableBufSize() const { - return ((wPos_ >= PROTO_MAX_STREAM_BUF_SIZE) ? 0 : (PROTO_MAX_STREAM_BUF_SIZE - wPos_)); + return ((wPos_ >= MAX_STREAM_BUF_SIZE) ? 0 : (MAX_STREAM_BUF_SIZE - wPos_)); } bool StreamBuffer::ChkRWError() const @@ -184,7 +184,6 @@ const std::string &StreamBuffer::GetErrorStatusRemark() const {ErrorStatus::ERROR_STATUS_WRITE, "WRITE_ERROR"}, }; static const std::string invalidStatus { "UNKNOWN" }; - auto tIter = std::find_if(remark.cbegin(), remark.cend(), [this](const auto &item) { return (item.first == rwErrorStatus_); }); diff --git a/utils/ipc/src/stream_session.cpp b/utils/ipc/src/stream_session.cpp index dd837974..257f96f3 100644 --- a/utils/ipc/src/stream_session.cpp +++ b/utils/ipc/src/stream_session.cpp @@ -47,7 +47,7 @@ StreamSession::StreamSession(const std::string &programName, const int32_t modul bool StreamSession::SendMsg(const char *buf, size_t size) const { CHKPF(buf); - if ((size == 0) || (size > PROTO_MAX_PACKET_BUF_SIZE)) { + if ((size == 0) || (size > MAX_PACKET_BUF_SIZE)) { SEN_HILOGE("Buf size:%{public}zu", size); return false; } @@ -55,17 +55,15 @@ bool StreamSession::SendMsg(const char *buf, size_t size) const SEN_HILOGE("The fd_ is less than 0"); return false; } - - int32_t idx = 0; - int32_t retryCount = 0; - const int32_t bufSize = static_cast(size); - int32_t remSize = bufSize; - while (remSize > 0 && retryCount < PROTO_SEND_RETRY_LIMIT) { + size_t idx = 0; + size_t retryCount = 0; + size_t remSize = size; + while (remSize > 0 && retryCount < SEND_RETRY_LIMIT) { retryCount += 1; auto count = send(fd_, &buf[idx], remSize, MSG_DONTWAIT | MSG_NOSIGNAL); if (count < 0) { if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) { - usleep(PROTO_SEND_RETRY_SLEEP_TIME); + usleep(SEND_RETRY_SLEEP_TIME); SEN_HILOGW("Continue for errno EAGAIN|EINTR|EWOULDBLOCK, errno:%{public}d", errno); continue; } @@ -75,12 +73,12 @@ bool StreamSession::SendMsg(const char *buf, size_t size) const idx += count; remSize -= count; if (remSize > 0) { - usleep(PROTO_SEND_RETRY_SLEEP_TIME); + usleep(SEND_RETRY_SLEEP_TIME); } } - if (retryCount >= PROTO_SEND_RETRY_LIMIT || remSize != 0) { - SEN_HILOGE("Send too many times:%{public}d/%{public}d,size:%{public}d/%{public}d fd:%{public}d", - retryCount, PROTO_SEND_RETRY_LIMIT, idx, bufSize, fd_); + if (retryCount >= SEND_RETRY_LIMIT || remSize != 0) { + SEN_HILOGE("Send too many times:%{public}zu/%{public}zu, size:%{public}zu/%{public}zu, fd:%{public}d", + retryCount, SEND_RETRY_LIMIT, idx, size, fd_); return false; } return true; @@ -88,7 +86,6 @@ bool StreamSession::SendMsg(const char *buf, size_t size) const void StreamSession::Close() { - SEN_HILOGD("Enter fd_:%{public}d.", fd_); if (fd_ >= 0) { close(fd_); fd_ = -1; @@ -113,7 +110,7 @@ void StreamSession::UpdateDescript() bool StreamSession::SendMsg(NetPacket &pkt) const { if (pkt.ChkRWError()) { - SEN_HILOGE("Read and write status is error"); + SEN_HILOGE("Read and write status failed"); return false; } StreamBuffer buf; diff --git a/utils/ipc/src/stream_socket.cpp b/utils/ipc/src/stream_socket.cpp index 1a2044df..77f71172 100644 --- a/utils/ipc/src/stream_socket.cpp +++ b/utils/ipc/src/stream_socket.cpp @@ -64,7 +64,7 @@ int32_t StreamSocket::EpollCtl(int32_t fd, int32_t op, struct epoll_event &event ret = epoll_ctl(epollFd, op, fd, &event); } if (ret < 0) { - SEN_HILOGE("Epoll_ctl return %{public}d,epollFd_:%{public}d, op:%{public}d,fd:%{public}d,errno:%{public}d", + SEN_HILOGE("Epoll_ctl ret:%{public}d, epollFd_:%{public}d, op:%{public}d, fd:%{public}d, errno:%{public}d", ret, epollFd, op, fd, errno); } return ret; @@ -81,27 +81,27 @@ int32_t StreamSocket::EpollWait(struct epoll_event &events, int32_t maxevents, i } auto ret = epoll_wait(epollFd, &events, maxevents, timeout); if (ret < 0) { - SEN_HILOGE("Epoll_wait ret:%{public}d,errno:%{public}d", ret, errno); + SEN_HILOGE("Epoll_wait ret:%{public}d, errno:%{public}d", ret, errno); } return ret; } void StreamSocket::OnReadPackets(CircleStreamBuffer &circBuf, StreamSocket::PacketCallBackFun callbackFun) { - constexpr int32_t headSize = static_cast(sizeof(PackHead)); - for (int32_t i = 0; i < PROTO_ONCE_PROCESS_NETPACKET_LIMIT; i++) { - const int32_t unreadSize = circBuf.UnreadSize(); + constexpr size_t headSize = sizeof(PackHead); + for (size_t i = 0; i < ONCE_PROCESS_NETPACKET_LIMIT; i++) { + const size_t unreadSize = circBuf.UnreadSize(); if (unreadSize < headSize) { break; } - int32_t dataSize = unreadSize - headSize; + size_t dataSize = unreadSize - headSize; char *buf = const_cast(circBuf.ReadBuf()); CHKPB(buf); PackHead *head = reinterpret_cast(buf); CHKPB(head); - if (head->size < 0 || head->size > PROTO_MAX_PACKET_BUF_SIZE) { + if (head->size < 0 || head->size > MAX_PACKET_BUF_SIZE) { SEN_HILOGE("Packet header parsing error, and this error cannot be recovered. The buffer will be reset." - " head->size:%{public}d, unreadSize:%{public}d", head->size, unreadSize); + " head->size:%{public}zu, unreadSize:%{public}zu", head->size, unreadSize); circBuf.Reset(); break; } @@ -111,12 +111,12 @@ void StreamSocket::OnReadPackets(CircleStreamBuffer &circBuf, StreamSocket::Pack NetPacket pkt(head->idMsg); if ((head->size > 0) && (!pkt.Write(&buf[headSize], head->size))) { SEN_HILOGW("Error writing data in the NetPacket. It will be retried next time. messageid:%{public}d," - "size:%{public}d", head->idMsg, head->size); + "size:%{public}zu", head->idMsg, head->size); break; } if (!circBuf.SeekReadPos(pkt.GetPacketLength())) { SEN_HILOGW("Set read position error, and this error cannot be recovered, and the buffer will be reset." - " packetSize:%{public}d unreadSize:%{public}d", pkt.GetPacketLength(), unreadSize); + " packetSize:%{public}zu, unreadSize:%{public}zu", pkt.GetPacketLength(), unreadSize); circBuf.Reset(); break; } @@ -141,7 +141,7 @@ void StreamSocket::Close() if (fd_ >= 0) { auto rf = close(fd_); if (rf > 0) { - SEN_HILOGE("Socket close failed rf:%{public}d", rf); + SEN_HILOGE("Socket close failed, rf:%{public}d", rf); } } fd_ = -1; -- Gitee From 9d979df3244cbe0b07768f269c17f34e743e7797 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Thu, 9 Mar 2023 11:21:48 +0000 Subject: [PATCH 18/53] update Signed-off-by: hui1975 Change-Id: I3587fdd0e4445b93c27d07f7a901a4f4631e0d93 --- utils/ipc/include/proto.h | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/utils/ipc/include/proto.h b/utils/ipc/include/proto.h index d0250198..c846508b 100644 --- a/utils/ipc/include/proto.h +++ b/utils/ipc/include/proto.h @@ -20,10 +20,8 @@ namespace OHOS { namespace Sensors { -#define SEND_RETRY_LIMIT 32 -#define SEND_RETRY_SLEEP_TIME 10000 - - +static const size_t SEND_RETRY_LIMIT = 32; +static const size_t SEND_RETRY_SLEEP_TIME = 10000; static const size_t MAX_VECTOR_SIZE = 10; static const size_t MAX_SESSON_ALARM = 100; static const size_t MAX_RECV_LIMIT = 13; -- Gitee From 79d88c760a95d8d1318d78f19e3aefc6dd4021f0 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Thu, 9 Mar 2023 13:45:55 +0000 Subject: [PATCH 19/53] update Signed-off-by: hui1975 Change-Id: Iddc014944405459dd48af23e4cf84693c4953de4 --- frameworks/native/sensor/src/fd_listener.cpp | 2 +- services/sensor/src/stream_server.cpp | 2 +- utils/ipc/include/net_packet.h | 6 +++--- utils/ipc/src/circle_stream_buffer.cpp | 2 +- utils/ipc/src/net_packet.cpp | 2 -- 5 files changed, 6 insertions(+), 8 deletions(-) diff --git a/frameworks/native/sensor/src/fd_listener.cpp b/frameworks/native/sensor/src/fd_listener.cpp index 527ccaed..4fcd303a 100644 --- a/frameworks/native/sensor/src/fd_listener.cpp +++ b/frameworks/native/sensor/src/fd_listener.cpp @@ -52,7 +52,7 @@ void FdListener::OnReadable(int32_t fd) SEN_HILOGE("Recv return %{public}zu, errno:%{public}d", size, errno); break; } else { - SEN_HILOGD("The service side disconnect with the client. size:0, count:%{public}d, errno:%{public}d", + SEN_HILOGD("The service side disconnect with the client. size:0, count:%{public}zu, errno:%{public}d", i, errno); break; } diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index 6d50583e..df7f2c92 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -183,7 +183,7 @@ bool StreamServer::AddSession(SessionPtr ses) return false; } if (sessionsMap_.size() > MAX_SESSON_ALARM) { - SEN_HILOGE("Too many clients. Warning Value:%{public}d, Current Value:%{public}zd", + SEN_HILOGE("Too many clients. Warning Value:%{public}zu, Current Value:%{public}zu", MAX_SESSON_ALARM, sessionsMap_.size()); return false; } diff --git a/utils/ipc/include/net_packet.h b/utils/ipc/include/net_packet.h index c88d1099..6bf4e501 100644 --- a/utils/ipc/include/net_packet.h +++ b/utils/ipc/include/net_packet.h @@ -22,7 +22,7 @@ #pragma pack(1) using PACKHEAD = struct PackHead { OHOS::Sensors::MessageId idMsg; - int32_t size; + size_t size; }; #pragma pack() @@ -34,8 +34,8 @@ public: explicit NetPacket(MessageId msgId); NetPacket(const NetPacket &pkt); NetPacket &operator = (const NetPacket &pkt); - virtual ~NetPacket(); - virtual void MakeData(StreamBuffer &buf) const; + ~NetPacket() = default; + void MakeData(StreamBuffer &buf) const; size_t GetSize() const; size_t GetPacketLength() const; const char* GetData() const; diff --git a/utils/ipc/src/circle_stream_buffer.cpp b/utils/ipc/src/circle_stream_buffer.cpp index 11bb9409..c086b695 100644 --- a/utils/ipc/src/circle_stream_buffer.cpp +++ b/utils/ipc/src/circle_stream_buffer.cpp @@ -32,7 +32,7 @@ bool CircleStreamBuffer::CheckWrite(size_t size) bool CircleStreamBuffer::Write(const char *buf, size_t size) { if (!CheckWrite(size)) { - SEN_HILOGE("Out of buffer memory, availableSize:%{public}zu, size:%{public}zu," + SEN_HILOGE("Buffer is overflow, availableSize:%{public}zu, size:%{public}zu," "unreadSize:%{public}zu, rPos:%{public}zu, wPos:%{public}zu", GetAvailableBufSize(), size, UnreadSize(), rPos_, wPos_); return false; diff --git a/utils/ipc/src/net_packet.cpp b/utils/ipc/src/net_packet.cpp index 6a0b62fe..27dec89b 100644 --- a/utils/ipc/src/net_packet.cpp +++ b/utils/ipc/src/net_packet.cpp @@ -27,8 +27,6 @@ NetPacket::NetPacket(const NetPacket &pkt) : NetPacket(pkt.GetMsgId()) Clone(pkt); } -NetPacket::~NetPacket() {} - void NetPacket::MakeData(StreamBuffer &buf) const { PACKHEAD head = {msgId_, wPos_}; -- Gitee From 600bd29ea81efde171ed2e0fbd81b85334413e7a Mon Sep 17 00:00:00 2001 From: hui1975 Date: Fri, 10 Mar 2023 09:10:37 +0000 Subject: [PATCH 20/53] update Signed-off-by: hui1975 Change-Id: I314b8416d343e4f2c63eda2ad5497db736b6df3d --- services/sensor/src/stream_server.cpp | 3 +-- utils/ipc/include/stream_session.h | 7 ++----- utils/ipc/src/stream_session.cpp | 10 +--------- 3 files changed, 4 insertions(+), 16 deletions(-) diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index df7f2c92..3441b99b 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -110,7 +110,6 @@ int32_t StreamServer::AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenT { CALL_LOG_ENTER; std::string programName = ""; - int32_t moduleType = 0; int32_t sockFds[2] = { -1 }; if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockFds) != 0) { SEN_HILOGE("Call socketpair failed, errno:%{public}d", errno); @@ -152,7 +151,7 @@ int32_t StreamServer::AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenT goto CLOSE_SOCK; } } - sess = std::make_shared(programName, moduleType, serverFd, uid, pid); + sess = std::make_shared(programName, serverFd, uid, pid); sess->SetTokenType(tokenType); if (!AddSession(sess)) { SEN_HILOGE("AddSession fail"); diff --git a/utils/ipc/include/stream_session.h b/utils/ipc/include/stream_session.h index eba3fb1a..e94e8373 100644 --- a/utils/ipc/include/stream_session.h +++ b/utils/ipc/include/stream_session.h @@ -36,15 +36,13 @@ using SessionPtr = std::shared_ptr; using namespace Security::AccessToken; class StreamSession : public std::enable_shared_from_this { public: - StreamSession(const std::string &programName, const int32_t moduleType, const int32_t fd, const int32_t uid, - const int32_t pid); - virtual ~StreamSession() = default; + StreamSession(const std::string &programName, const int32_t fd, const int32_t uid, const int32_t pid); + ~StreamSession() = default; bool SendMsg(const char *buf, size_t size) const; bool SendMsg(NetPacket &pkt) const; void Close(); int32_t GetUid() const; int32_t GetPid() const; - int32_t GetModuleType() const; SessionPtr GetSharedPtr(); int32_t GetFd() const; const std::string& GetDescript() const; @@ -63,7 +61,6 @@ protected: std::map> events_; std::string descript_; const std::string programName_; - const int32_t moduleType_ { -1 }; int32_t fd_ { -1 }; const int32_t uid_ { -1 }; const int32_t pid_ { -1 }; diff --git a/utils/ipc/src/stream_session.cpp b/utils/ipc/src/stream_session.cpp index 257f96f3..57390533 100644 --- a/utils/ipc/src/stream_session.cpp +++ b/utils/ipc/src/stream_session.cpp @@ -33,10 +33,8 @@ namespace { constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "StreamSession" }; } -StreamSession::StreamSession(const std::string &programName, const int32_t moduleType, const int32_t fd, - const int32_t uid, const int32_t pid) +StreamSession::StreamSession(const std::string &programName, const int32_t fd, const int32_t uid, const int32_t pid) : programName_(programName), - moduleType_(moduleType), fd_(fd), uid_(uid), pid_(pid) @@ -98,7 +96,6 @@ void StreamSession::UpdateDescript() std::ostringstream oss; oss << "fd = " << fd_ << ", programName = " << programName_ - << ", moduleType = " << moduleType_ << ((fd_ < 0) ? ", closed" : ", opened") << ", uid = " << uid_ << ", pid = " << pid_ @@ -128,11 +125,6 @@ int32_t StreamSession::GetPid() const return pid_; } -int32_t StreamSession::GetModuleType() const -{ - return moduleType_; -} - SessionPtr StreamSession::GetSharedPtr() { return shared_from_this(); -- Gitee From 759c65be703f579fc4ad92541fc8a8f84afef092 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Thu, 16 Mar 2023 02:30:49 +0000 Subject: [PATCH 21/53] update Signed-off-by: hui1975 Change-Id: Ic087bb006fb423a4b9039e58c1458dfaece569dc --- utils/ipc/src/stream_buffer.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/utils/ipc/src/stream_buffer.cpp b/utils/ipc/src/stream_buffer.cpp index 53764b97..92573128 100644 --- a/utils/ipc/src/stream_buffer.cpp +++ b/utils/ipc/src/stream_buffer.cpp @@ -75,7 +75,7 @@ bool StreamBuffer::Read(std::string &buf) bool StreamBuffer::Write(const std::string &buf) { - return Write(buf.c_str(), buf.length()+1); + return Write(buf.c_str(), buf.length() + 1); } bool StreamBuffer::Read(StreamBuffer &buf) @@ -115,7 +115,7 @@ bool StreamBuffer::Read(char *buf, size_t size) return false; } rPos_ += size; - rCount_ += 1; + ++rCount_; return true; } @@ -147,7 +147,7 @@ bool StreamBuffer::Write(const char *buf, size_t size) return false; } wPos_ += size; - wCount_ += 1; + ++wCount_; return true; } -- Gitee From 5be2e4a78f30760eb2e857f7497d44908b7b1e22 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Sat, 18 Mar 2023 03:46:49 +0000 Subject: [PATCH 22/53] update Signed-off-by: hui1975 Change-Id: I7491429aef23258438e8c7fdbbddb238c538e949 --- services/sensor/include/sensor_service.h | 1 - 1 file changed, 1 deletion(-) diff --git a/services/sensor/include/sensor_service.h b/services/sensor/include/sensor_service.h index 5a8dfbf6..11bbb94a 100644 --- a/services/sensor/include/sensor_service.h +++ b/services/sensor/include/sensor_service.h @@ -84,7 +84,6 @@ private: SensorHdiConnection &sensorHdiConnection_ = SensorHdiConnection::GetInstance(); ClientInfo &clientInfo_ = ClientInfo::GetInstance(); SensorManager &sensorManager_ = SensorManager::GetInstance(); - FlushInfoRecord &flushInfo_ = FlushInfoRecord::GetInstance(); SensorPowerPolicy &sensorPowerPolicy_ = SensorPowerPolicy::GetInstance(); sptr sensorDataProcesser_ = nullptr; sptr reportDataCallback_ = nullptr; -- Gitee From fbf4b3da487dab88794916c1d93ff09836c27532 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Sat, 18 Mar 2023 04:00:41 +0000 Subject: [PATCH 23/53] update Signed-off-by: hui1975 Change-Id: I41ef0c809931a45b5faf299149eb2f606f9a507a --- utils/ipc/include/stream_socket.h | 2 +- utils/ipc/src/stream_session.cpp | 4 ++-- utils/ipc/src/stream_socket.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/utils/ipc/include/stream_socket.h b/utils/ipc/include/stream_socket.h index acae2006..cd6c498b 100644 --- a/utils/ipc/include/stream_socket.h +++ b/utils/ipc/include/stream_socket.h @@ -17,8 +17,8 @@ #define STREAM_SOCKET_H #include -#include #include +#include #include #include diff --git a/utils/ipc/src/stream_session.cpp b/utils/ipc/src/stream_session.cpp index 57390533..a4933fd8 100644 --- a/utils/ipc/src/stream_session.cpp +++ b/utils/ipc/src/stream_session.cpp @@ -24,8 +24,8 @@ #include #include "proto.h" -#include "stream_socket.h" #include "sensors_errors.h" +#include "stream_socket.h" namespace OHOS { namespace Sensors { @@ -57,7 +57,7 @@ bool StreamSession::SendMsg(const char *buf, size_t size) const size_t retryCount = 0; size_t remSize = size; while (remSize > 0 && retryCount < SEND_RETRY_LIMIT) { - retryCount += 1; + ++retryCount; auto count = send(fd_, &buf[idx], remSize, MSG_DONTWAIT | MSG_NOSIGNAL); if (count < 0) { if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) { diff --git a/utils/ipc/src/stream_socket.cpp b/utils/ipc/src/stream_socket.cpp index 77f71172..2179ea16 100644 --- a/utils/ipc/src/stream_socket.cpp +++ b/utils/ipc/src/stream_socket.cpp @@ -89,7 +89,7 @@ int32_t StreamSocket::EpollWait(struct epoll_event &events, int32_t maxevents, i void StreamSocket::OnReadPackets(CircleStreamBuffer &circBuf, StreamSocket::PacketCallBackFun callbackFun) { constexpr size_t headSize = sizeof(PackHead); - for (size_t i = 0; i < ONCE_PROCESS_NETPACKET_LIMIT; i++) { + for (size_t i = 0; i < ONCE_PROCESS_NETPACKET_LIMIT; ++i) { const size_t unreadSize = circBuf.UnreadSize(); if (unreadSize < headSize) { break; -- Gitee From e30e69c7482a0d75f95b1810d47e5898d5c203a2 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Wed, 22 Mar 2023 06:13:45 +0000 Subject: [PATCH 24/53] update Signed-off-by: hui1975 Change-Id: I43f99ca4b1efee731229253d039cfa82c9edd35e --- services/sensor/src/client_info.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/sensor/src/client_info.cpp b/services/sensor/src/client_info.cpp index 2db33b12..754d4efc 100644 --- a/services/sensor/src/client_info.cpp +++ b/services/sensor/src/client_info.cpp @@ -736,6 +736,9 @@ bool ClientInfo::IsUnregisterClientDeathRecipient(int32_t pid) return false; } return true; +} + + int32_t ClientInfo::GetPidByTokenId(AccessTokenID tokenId) { std::lock_guard uidLock(uidMutex_); -- Gitee From de720436e56a6a542366354943428efcc6e329ee Mon Sep 17 00:00:00 2001 From: hui1975 Date: Wed, 22 Mar 2023 07:14:38 +0000 Subject: [PATCH 25/53] update Signed-off-by: hui1975 Change-Id: I5c15dbe51b7e15993409429ae1f2e1ac7a858c71 --- services/sensor/include/stream_server.h | 6 +----- services/sensor/src/sensor_service.cpp | 2 ++ 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/services/sensor/include/stream_server.h b/services/sensor/include/stream_server.h index 32d3c590..03e1ba7d 100644 --- a/services/sensor/include/stream_server.h +++ b/services/sensor/include/stream_server.h @@ -19,15 +19,12 @@ #include #include -#include "nocopyable.h" -#include "refbase.h" - #include "stream_session.h" #include "stream_socket.h" namespace OHOS { namespace Sensors { -class StreamServer : public RefBase, public StreamSocket { +class StreamServer : public StreamSocket { public: StreamServer() = default; virtual ~StreamServer(); @@ -38,7 +35,6 @@ public: SessionPtr GetSession(int32_t fd); SessionPtr GetSessionByPid(int32_t pid); int32_t AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenType, int32_t &serverFd, int32_t &clientFd); - DISALLOW_COPY_AND_MOVE(StreamServer); protected: bool AddSession(SessionPtr ses); diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index a3b686c7..1a26a72b 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -512,6 +512,8 @@ void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid) ActiveInfo activeInfo(pid, sensorId, sensorInfo.GetSamplingPeriodNs(), sensorInfo.GetMaxReportDelayNs()); sensorPowerPolicy_.ReportActiveInfo(activeInfo, sessionList); +} + bool SensorService::RegisterPermCallback() { Security::AccessToken::PermStateChangeScope scope = { -- Gitee From 67f1124fdcbab645ba1797c2c63b2f2983141716 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Wed, 22 Mar 2023 09:54:00 +0000 Subject: [PATCH 26/53] update Signed-off-by: hui1975 Change-Id: Ib6b0922cd2b562df4fc3adb76154d6bd2a648e95 --- frameworks/native/sensor/include/sensor_data_channel.h | 4 ++-- frameworks/native/sensor/include/sensor_service_client.h | 7 +++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/frameworks/native/sensor/include/sensor_data_channel.h b/frameworks/native/sensor/include/sensor_data_channel.h index f6ef699c..df6778d1 100644 --- a/frameworks/native/sensor/include/sensor_data_channel.h +++ b/frameworks/native/sensor/include/sensor_data_channel.h @@ -16,14 +16,14 @@ #ifndef SENSOR_DATA_CHANNEL_H #define SENSOR_DATA_CHANNEL_H -#include #include #include +#include #include #include "sensor_agent_type.h" -#include "sensor_event_handler.h" #include "sensor_basic_data_channel.h" +#include "sensor_event_handler.h" namespace OHOS { namespace Sensors { diff --git a/frameworks/native/sensor/include/sensor_service_client.h b/frameworks/native/sensor/include/sensor_service_client.h index 944a8cbc..ea07be41 100755 --- a/frameworks/native/sensor/include/sensor_service_client.h +++ b/frameworks/native/sensor/include/sensor_service_client.h @@ -37,7 +37,7 @@ namespace OHOS { namespace Sensors { class SensorServiceClient : public StreamSocket, public Singleton { public: - ~SensorServiceClient(); + ~SensorServiceClient() override; std::vector GetSensorList(); int32_t EnableSensor(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay); int32_t DisableSensor(int32_t sensorId); @@ -57,6 +57,8 @@ private: int32_t InitServiceClient(); void UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay); void DeleteSensorInfoItem(int32_t sensorId); + int32_t CreateSocketChannel(); + void HandleNetPacke(NetPacket &pkt); std::mutex clientMutex_; sptr serviceDeathObserver_; sptr sensorServer_; @@ -65,9 +67,6 @@ private: sptr sensorClientStub_; std::mutex mapMutex_; std::map sensorInfoMap_; - - int32_t CreateSocketChannel(); - void HandleNetPacke(NetPacket &pkt); std::atomic_bool isConnected_ = false; CircleStreamBuffer circBuf_; std::mutex activeInfoCBMutex_; -- Gitee From 4bb9a1c2f65090c2d2b68186a81f748285180ba3 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Thu, 23 Mar 2023 02:30:15 +0000 Subject: [PATCH 27/53] update Signed-off-by: hui1975 Change-Id: I4da3065e9cae9ed0c7cfa412ced16a2bcc3c8954 --- utils/ipc/src/stream_socket.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/utils/ipc/src/stream_socket.cpp b/utils/ipc/src/stream_socket.cpp index 2179ea16..22bf4b34 100644 --- a/utils/ipc/src/stream_socket.cpp +++ b/utils/ipc/src/stream_socket.cpp @@ -37,9 +37,9 @@ int32_t StreamSocket::EpollCreate(int32_t size) { epollFd_ = epoll_create(size); if (epollFd_ < 0) { - SEN_HILOGE("Epoll_create return %{public}d", epollFd_); + SEN_HILOGE("Epoll create, epollFd_:%{public}d", epollFd_); } else { - SEN_HILOGI("Epoll_create, epollFd_:%{public}d", epollFd_); + SEN_HILOGI("Epoll already create, epollFd_:%{public}d", epollFd_); } return epollFd_; } @@ -54,7 +54,7 @@ int32_t StreamSocket::EpollCtl(int32_t fd, int32_t op, struct epoll_event &event epollFd = epollFd_; } if (epollFd < 0) { - SEN_HILOGE("Invalid param epollFd"); + SEN_HILOGE("Invalid param epollFd, epollFd_:%{public}d", epollFd_); return ERROR; } int32_t ret; @@ -76,7 +76,7 @@ int32_t StreamSocket::EpollWait(struct epoll_event &events, int32_t maxevents, i epollFd = epollFd_; } if (epollFd < 0) { - SEN_HILOGE("Invalid param epollFd"); + SEN_HILOGE("Invalid param epollFd, epollFd_:%{public}d", epollFd_); return ERROR; } auto ret = epoll_wait(epollFd, &events, maxevents, timeout); -- Gitee From f289048b905e6b8cc843ecc1aa3bea630d1af956 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 27 Mar 2023 12:16:20 +0000 Subject: [PATCH 28/53] update Signed-off-by: hui1975 Change-Id: I7838d630ed5e5e2c3472c0e8e3b5ad11ea5c9789 --- .../native/sensor/include/i_sensor_service.h | 2 +- .../sensor/include/sensor_service_proxy.h | 2 +- frameworks/native/sensor/src/fd_listener.cpp | 4 +- .../native/sensor/src/sensor_data_channel.cpp | 3 +- .../sensor/src/sensor_service_client.cpp | 2 +- .../sensor/src/sensor_service_proxy.cpp | 2 +- .../test/unittest/sensor_power_test.cpp | 12 ++-- services/sensor/include/sensor_power_policy.h | 4 +- services/sensor/include/sensor_service.h | 4 +- services/sensor/src/sensor_power_policy.cpp | 57 +++++++++---------- services/sensor/src/sensor_service.cpp | 23 +++----- services/sensor/src/sensor_service_stub.cpp | 11 ++-- services/sensor/src/stream_server.cpp | 4 +- utils/ipc/src/stream_socket.cpp | 2 +- 14 files changed, 61 insertions(+), 71 deletions(-) diff --git a/frameworks/native/sensor/include/i_sensor_service.h b/frameworks/native/sensor/include/i_sensor_service.h index d8ca66e7..26e28295 100755 --- a/frameworks/native/sensor/include/i_sensor_service.h +++ b/frameworks/native/sensor/include/i_sensor_service.h @@ -43,7 +43,7 @@ public: virtual ErrCode SuspendSensors(int32_t pid) = 0; virtual ErrCode ResumeSensors(int32_t pid) = 0; virtual ErrCode GetActiveInfoList(int32_t pid, std::vector &activeInfoList) = 0; - virtual ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) = 0; + virtual ErrCode CreateSocketChannel(const sptr &sensorClient, int32_t &clientFd) = 0; virtual ErrCode DestroySocketChannel(const sptr &sensorClient) = 0; virtual ErrCode EnableActiveInfoCB() = 0; virtual ErrCode DisableActiveInfoCB() = 0; diff --git a/frameworks/native/sensor/include/sensor_service_proxy.h b/frameworks/native/sensor/include/sensor_service_proxy.h index 59f5a375..b5fd2480 100755 --- a/frameworks/native/sensor/include/sensor_service_proxy.h +++ b/frameworks/native/sensor/include/sensor_service_proxy.h @@ -38,7 +38,7 @@ public: ErrCode SuspendSensors(int32_t pid) override; ErrCode ResumeSensors(int32_t pid) override; ErrCode GetActiveInfoList(int32_t pid, std::vector &activeInfoList) override; - ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) override; + ErrCode CreateSocketChannel(const sptr &sensorClient, int32_t &clientFd) override; ErrCode DestroySocketChannel(const sptr &sensorClient) override; ErrCode EnableActiveInfoCB() override; ErrCode DisableActiveInfoCB() override; diff --git a/frameworks/native/sensor/src/fd_listener.cpp b/frameworks/native/sensor/src/fd_listener.cpp index 4fcd303a..1a37a217 100644 --- a/frameworks/native/sensor/src/fd_listener.cpp +++ b/frameworks/native/sensor/src/fd_listener.cpp @@ -46,14 +46,14 @@ void FdListener::OnReadable(int32_t fd) } else if (size < 0) { if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) { SEN_HILOGW("Continue for errno EAGAIN|EINTR|EWOULDBLOCK, size:%{public}zu, errno:%{public}d", - size, errno); + size, errno); continue; } SEN_HILOGE("Recv return %{public}zu, errno:%{public}d", size, errno); break; } else { SEN_HILOGD("The service side disconnect with the client. size:0, count:%{public}zu, errno:%{public}d", - i, errno); + i, errno); break; } if (size < MAX_PACKET_BUF_SIZE) { diff --git a/frameworks/native/sensor/src/sensor_data_channel.cpp b/frameworks/native/sensor/src/sensor_data_channel.cpp index 7dd29d6d..c148592a 100644 --- a/frameworks/native/sensor/src/sensor_data_channel.cpp +++ b/frameworks/native/sensor/src/sensor_data_channel.cpp @@ -80,8 +80,7 @@ int32_t SensorDataChannel::InnerSensorDataChannel() int32_t SensorDataChannel::DestroySensorDataChannel() { - int32_t receiveFd = GetReceiveDataFd(); - DelFdListener(receiveFd); + DelFdListener(GetReceiveDataFd()); return DestroySensorBasicChannel(); } diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index 910032b6..8ad9c087 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -390,7 +390,7 @@ int32_t SensorServiceClient::CreateSocketChannel() CHKPR(sensorServer_, ERROR); int32_t clientFd = -1; StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel"); - ret = sensorServer_->CreateSocketChannel(clientFd, sensorClientStub_); + ret = sensorServer_->CreateSocketChannel(sensorClientStub_, clientFd); FinishTrace(HITRACE_TAG_SENSORS); if (!(ret == ERR_OK && clientFd >= 0)) { Close(); diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 0dd3ac7c..4651b120 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -278,7 +278,7 @@ ErrCode SensorServiceProxy::GetActiveInfoList(int32_t pid, std::vector(ret); } -ErrCode SensorServiceProxy::CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) +ErrCode SensorServiceProxy::CreateSocketChannel(const sptr &sensorClient, int32_t &clientFd) { CHKPR(sensorClient, OBJECT_NULL); MessageParcel data; diff --git a/interfaces/native/test/unittest/sensor_power_test.cpp b/interfaces/native/test/unittest/sensor_power_test.cpp index d7816721..2e1d2025 100644 --- a/interfaces/native/test/unittest/sensor_power_test.cpp +++ b/interfaces/native/test/unittest/sensor_power_test.cpp @@ -94,15 +94,15 @@ void SensorDataCallbackImpl(SensorEvent *event) void SensorActiveInfoCBImpl(SensorActiveInfo &sensorActiveInfo) { SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, samplingPeriodNs:%{public}" PRId64 ", " - "maxReportDelayNs:%{public}" PRId64 "", sensorActiveInfo.pid, sensorActiveInfo.sensorId, - sensorActiveInfo.samplingPeriodNs, sensorActiveInfo.maxReportDelayNs); + "maxReportDelayNs:%{public}" PRId64 "", sensorActiveInfo.pid, sensorActiveInfo.sensorId, + sensorActiveInfo.samplingPeriodNs, sensorActiveInfo.maxReportDelayNs); } void SensorActiveInfoCBImpl2(SensorActiveInfo &sensorActiveInfo) { SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, samplingPeriodNs:%{public}" PRId64 ", " - "maxReportDelayNs:%{public}" PRId64 "", sensorActiveInfo.pid, sensorActiveInfo.sensorId, - sensorActiveInfo.samplingPeriodNs, sensorActiveInfo.maxReportDelayNs); + "maxReportDelayNs:%{public}" PRId64 "", sensorActiveInfo.pid, sensorActiveInfo.sensorId, + sensorActiveInfo.samplingPeriodNs, sensorActiveInfo.maxReportDelayNs); } HWTEST_F(SensorPowerTest, SensorPowerTest_001, TestSize.Level1) @@ -199,8 +199,8 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_007, TestSize.Level1) for (int32_t i = 0; i < count; ++i) { SensorActiveInfo *curSensorActiveInfo = sensorActiveInfos + i; SEN_HILOGI("pid:%{public}d, sensorId:%{public}d, samplingPeriodNs:%{public}" PRId64 ", " - "maxReportDelayNs:%{public}" PRId64 "", curSensorActiveInfo->pid, curSensorActiveInfo->sensorId, - curSensorActiveInfo->samplingPeriodNs, curSensorActiveInfo->maxReportDelayNs); + "maxReportDelayNs:%{public}" PRId64 "", curSensorActiveInfo->pid, curSensorActiveInfo->sensorId, + curSensorActiveInfo->samplingPeriodNs, curSensorActiveInfo->maxReportDelayNs); } ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); diff --git a/services/sensor/include/sensor_power_policy.h b/services/sensor/include/sensor_power_policy.h index 7433ecee..cba4d092 100644 --- a/services/sensor/include/sensor_power_policy.h +++ b/services/sensor/include/sensor_power_policy.h @@ -40,8 +40,8 @@ public: private: bool CheckFreezingSensor(int32_t sensorId); - bool Suspend(std::unordered_map &SensorInfoMap, - std::vector &sensorIdList, int32_t pid); + bool Suspend(int32_t pid, std::vector &sensorIdList, + std::unordered_map &SensorInfoMap); bool Resume(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); ErrCode RestoreSensorInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); SensorHdiConnection &sensorHdiConnection_ = SensorHdiConnection::GetInstance(); diff --git a/services/sensor/include/sensor_service.h b/services/sensor/include/sensor_service.h index f2eaedd1..f5f0afa5 100644 --- a/services/sensor/include/sensor_service.h +++ b/services/sensor/include/sensor_service.h @@ -59,7 +59,7 @@ public: ErrCode SuspendSensors(int32_t pid) override; ErrCode ResumeSensors(int32_t pid) override; ErrCode GetActiveInfoList(int32_t pid, std::vector &activeInfoList) override; - ErrCode CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) override; + ErrCode CreateSocketChannel(const sptr &sensorClient, int32_t &clientFd) override; ErrCode DestroySocketChannel(const sptr &sensorClient) override; ErrCode EnableActiveInfoCB() override; ErrCode DisableActiveInfoCB() override; @@ -88,6 +88,7 @@ private: ErrCode DisableSensor(int32_t sensorId, int32_t pid); bool RegisterPermCallback(); void UnregisterPermCallback(); + void ReportActiveInfo(int32_t sensorId, int32_t pid); SensorServiceState state_; std::mutex serviceLock_; std::mutex sensorsMutex_; @@ -106,7 +107,6 @@ private: std::shared_ptr permStateChangeCb_; ErrCode SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); std::atomic_bool isReportActiveInfo_ = false; - void ReportActiveInfo(int32_t sensorId, int32_t pid); }; } // namespace Sensors } // namespace OHOS diff --git a/services/sensor/src/sensor_power_policy.cpp b/services/sensor/src/sensor_power_policy.cpp index 9899efce..cfe41444 100644 --- a/services/sensor/src/sensor_power_policy.cpp +++ b/services/sensor/src/sensor_power_policy.cpp @@ -37,29 +37,24 @@ ErrCode SensorPowerPolicy::SuspendSensors(int32_t pid) { CALL_LOG_ENTER; std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); + if (sensorIdList.empty()) { + SEN_HILOGW("SensorIdList is empty, pid not enable sensor or all sensor have bean suspend"); + return ERR_OK; + } std::lock_guard pidSensorInfoLock(pidSensorInfoMutex_); auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); if (pidSensorInfoIt != pidSensorInfoMap_.end()) { - if (sensorIdList.empty()) { - SEN_HILOGD("Pid already suspend, all sensors suspend success, not need suspend again"); - return ERR_OK; - } else { - SEN_HILOGD("Pid already suspend, some sensors suspend failed, suspend these sensors again"); - std::unordered_map SensorInfoMap = pidSensorInfoIt->second; - if (!Suspend(SensorInfoMap, sensorIdList, pid)) { - SEN_HILOGE("Some sensor suspend failed"); - return DISABLE_SENSOR_ERR; - } - return ERR_OK; + SEN_HILOGI("Pid already call suspend, but some sensors suspend failed, suspend these sensors again"); + std::unordered_map sensorInfoMap = pidSensorInfoIt->second; + if (!Suspend(pid, sensorIdList, sensorInfoMap)) { + SEN_HILOGE("Some sensor suspend failed"); + return DISABLE_SENSOR_ERR; } + return ERR_OK; } - if (sensorIdList.empty()) { - SEN_HILOGE("Pid sensorId list is empty"); - return ERROR; - } - std::unordered_map SensorInfoMap; - auto isAllSuspend = Suspend(SensorInfoMap, sensorIdList, pid); - pidSensorInfoMap_.insert(std::make_pair(pid, SensorInfoMap)); + std::unordered_map sensorInfoMap; + auto isAllSuspend = Suspend(pid, sensorIdList, sensorInfoMap); + pidSensorInfoMap_.insert(std::make_pair(pid, sensorInfoMap)); if (!isAllSuspend) { SEN_HILOGE("Some sensor suspend failed"); return DISABLE_SENSOR_ERR; @@ -67,8 +62,8 @@ ErrCode SensorPowerPolicy::SuspendSensors(int32_t pid) return ERR_OK; } -bool SensorPowerPolicy::Suspend(std::unordered_map &SensorInfoMap, - std::vector &sensorIdList, int32_t pid) +bool SensorPowerPolicy::Suspend(int32_t pid, std::vector &sensorIdList, + std::unordered_map &sensorInfoMap) { CALL_LOG_ENTER; bool isAllSuspend = true; @@ -80,7 +75,7 @@ bool SensorPowerPolicy::Suspend(std::unordered_map &Se auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { SEN_HILOGD("Other client is using this sensor now, cannot suspend"); - SensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); + sensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); continue; } if (sensorHdiConnection_.DisableSensor(sensorId) != ERR_OK) { @@ -88,7 +83,7 @@ bool SensorPowerPolicy::Suspend(std::unordered_map &Se isAllSuspend = false; continue; } - SensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); + sensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); sensorManager_.AfterDisableSensor(sensorId); } return isAllSuspend; @@ -104,8 +99,8 @@ ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) return ERROR; } bool isAllResume = true; - std::unordered_map SensorInfoMap = pidSensorInfoIt->second; - for (auto sensorIt = SensorInfoMap.begin(); sensorIt != SensorInfoMap.end();) { + std::unordered_map sensorInfoMap = pidSensorInfoIt->second; + for (auto sensorIt = sensorInfoMap.begin(); sensorIt != sensorInfoMap.end();) { int32_t sensorId = sensorIt->first; int64_t samplingPeriodNs = sensorIt->second.GetSamplingPeriodNs(); int64_t maxReportDelayNs = sensorIt->second.GetMaxReportDelayNs(); @@ -114,7 +109,7 @@ ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) isAllResume = false; ++sensorIt; } else { - sensorIt = SensorInfoMap.erase(sensorIt); + sensorIt = sensorInfoMap.erase(sensorIt); } } if (!isAllResume) { @@ -126,16 +121,16 @@ ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) } bool SensorPowerPolicy::Resume(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, - int64_t maxReportDelayNs) + int64_t maxReportDelayNs) { CALL_LOG_ENTER; - if ((sensorId == INVALID_SENSOR_ID) || (samplingPeriodNs == 0) || + if ((sensorId == INVALID_SENSOR_ID) || (samplingPeriodNs <= 0) || ((samplingPeriodNs != 0L) && (maxReportDelayNs / samplingPeriodNs > MAX_EVENT_COUNT))) { SEN_HILOGE("SensorId is invalid or maxReportDelayNs exceed the maximum value"); return false; } if (clientInfo_.GetSensorState(sensorId)) { - SEN_HILOGD("Sensor has been resume already, sensorId:%{public}d", sensorId); + SEN_HILOGD("Sensor is enable, sensorId:%{public}d", sensorId); auto ret = RestoreSensorInfo(pid, sensorId, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { SEN_HILOGE("Restore sensor info failed, ret:%{public}d", ret); @@ -158,7 +153,7 @@ bool SensorPowerPolicy::Resume(int32_t pid, int32_t sensorId, int64_t samplingPe } ErrCode SensorPowerPolicy::RestoreSensorInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, - int64_t maxReportDelayNs) + int64_t maxReportDelayNs) { CALL_LOG_ENTER; auto ret = sensorManager_.SaveSubscriber(sensorId, pid, samplingPeriodNs, maxReportDelayNs); @@ -182,13 +177,13 @@ void SensorPowerPolicy::GetActiveInfoList(int32_t pid, std::vector & for (auto &sensorId : sensorIdList) { auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); ActiveInfo activeInfo(pid, sensorId, sensorInfo.GetSamplingPeriodNs(), - sensorInfo.GetMaxReportDelayNs()); + sensorInfo.GetMaxReportDelayNs()); activeInfoList.push_back(activeInfo); } } void SensorPowerPolicy::ReportActiveInfo(ActiveInfo activeInfo, - const std::vector &sessionList) + const std::vector &sessionList) { CALL_LOG_ENTER; NetPacket pkt(MessageId::ACTIVE_INFO); diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 1a26a72b..1279aa85 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -455,28 +455,25 @@ ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector &a return ERR_OK; } -ErrCode SensorService::CreateSocketChannel(int32_t &clientFd, const sptr &sensorClient) +ErrCode SensorService::CreateSocketChannel(const sptr &sensorClient, int32_t &clientFd) { CALL_LOG_ENTER; - int32_t uid = GetCallingUid(); - int32_t pid = GetCallingPid(); - int32_t tokenType = AccessTokenKit::GetTokenTypeFlag(GetCallingTokenID()); int32_t serverFd = -1; - clientFd = -1; - int32_t ret = AddSocketPairInfo(uid, pid, tokenType, serverFd, std::ref(clientFd)); + int32_t ret = AddSocketPairInfo(GetCallingUid(), GetCallingPid(), + AccessTokenKit::GetTokenTypeFlag(GetCallingTokenID()), + serverFd, std::ref(clientFd)); if (ret != ERR_OK) { SEN_HILOGE("Add socket pair info failed, ret:%{public}d", ret); return ret; } - RegisterClientDeathRecipient(sensorClient, pid); + RegisterClientDeathRecipient(sensorClient, GetCallingPid()); return ERR_OK; } ErrCode SensorService::DestroySocketChannel(const sptr &sensorClient) { CALL_LOG_ENTER; - int32_t pid = GetCallingPid(); - DelSession(pid); + DelSession(GetCallingPid()); UnregisterClientDeathRecipient(sensorClient); return ERR_OK; } @@ -485,16 +482,14 @@ ErrCode SensorService::EnableActiveInfoCB() { CALL_LOG_ENTER; isReportActiveInfo_ = true; - int32_t pid = GetCallingPid(); - return clientInfo_.AddActiveInfoCBPid(pid); + return clientInfo_.AddActiveInfoCBPid(GetCallingPid()); } ErrCode SensorService::DisableActiveInfoCB() { CALL_LOG_ENTER; isReportActiveInfo_ = false; - int32_t pid = GetCallingPid(); - return clientInfo_.DelActiveInfoCBPid(pid); + return clientInfo_.DelActiveInfoCBPid(GetCallingPid()); } void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid) @@ -510,7 +505,7 @@ void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid) } SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); ActiveInfo activeInfo(pid, sensorId, sensorInfo.GetSamplingPeriodNs(), - sensorInfo.GetMaxReportDelayNs()); + sensorInfo.GetMaxReportDelayNs()); sensorPowerPolicy_.ReportActiveInfo(activeInfo, sessionList); } diff --git a/services/sensor/src/sensor_service_stub.cpp b/services/sensor/src/sensor_service_stub.cpp index f9d88729..699bf1e6 100755 --- a/services/sensor/src/sensor_service_stub.cpp +++ b/services/sensor/src/sensor_service_stub.cpp @@ -205,7 +205,11 @@ ErrCode SensorServiceStub::GetActiveInfoListInner(MessageParcel &data, MessagePa return ERROR; } std::vector activeInfoList; - GetActiveInfoList(pid, activeInfoList); + int32_t ret = GetActiveInfoList(pid, activeInfoList); + if (ret != ERR_OK) { + SEN_HILOGE("Get activeInfo list failed"); + return ret; + } int32_t activeInfoCount = int32_t { activeInfoList.size() }; reply.WriteInt32(activeInfoCount); for (int32_t i = 0; i < activeInfoCount; i++) { @@ -222,12 +226,9 @@ ErrCode SensorServiceStub::CreateSocketChannelInner(MessageParcel &data, Message sptr sensorClient = data.ReadRemoteObject(); CHKPR(sensorClient, OBJECT_NULL); int32_t clientFd = -1; - int32_t ret = CreateSocketChannel(clientFd, sensorClient); + int32_t ret = CreateSocketChannel(sensorClient, clientFd); if (ret != ERR_OK) { SEN_HILOGE("Create socket channel failed"); - if (clientFd >= 0) { - close(clientFd); - } return ret; } if (!reply.WriteFileDescriptor(clientFd)) { diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index 3441b99b..ed7d02a5 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -106,7 +106,7 @@ SessionPtr StreamServer::GetSessionByPid(int32_t pid) } int32_t StreamServer::AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenType, - int32_t &serverFd, int32_t &clientFd) + int32_t &serverFd, int32_t &clientFd) { CALL_LOG_ENTER; std::string programName = ""; @@ -211,7 +211,7 @@ void StreamServer::DelSession(int32_t pid) } if (fd >= 0) { auto rf = close(fd); - if (rf > 0) { + if (rf != 0) { SEN_HILOGE("Socket fd close failed, rf:%{public}d", rf); } } diff --git a/utils/ipc/src/stream_socket.cpp b/utils/ipc/src/stream_socket.cpp index d2ca0c9b..9dd64d54 100644 --- a/utils/ipc/src/stream_socket.cpp +++ b/utils/ipc/src/stream_socket.cpp @@ -140,7 +140,7 @@ void StreamSocket::Close() { if (fd_ >= 0) { auto rf = close(fd_); - if (rf > 0) { + if (rf != 0) { SEN_HILOGE("Socket close failed, rf:%{public}d", rf); } } -- Gitee From ae976660de082d41be82c8aafe180a2b5d76e7cc Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 27 Mar 2023 12:37:47 +0000 Subject: [PATCH 29/53] update Signed-off-by: hui1975 Change-Id: I1429ce7f8adaafa4189401de459d670e244efc2d --- services/sensor/include/sensor_power_policy.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/sensor/include/sensor_power_policy.h b/services/sensor/include/sensor_power_policy.h index cba4d092..daf960d1 100644 --- a/services/sensor/include/sensor_power_policy.h +++ b/services/sensor/include/sensor_power_policy.h @@ -31,7 +31,7 @@ namespace OHOS { namespace Sensors { -class SensorPowerPolicy : public Singleton{ +class SensorPowerPolicy : public Singleton { public: ErrCode SuspendSensors(int32_t pid); ErrCode ResumeSensors(int32_t pid); -- Gitee From 2933f72197c66c0ce97cbc7c74fc52c462908928 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Wed, 29 Mar 2023 03:40:11 +0000 Subject: [PATCH 30/53] update Signed-off-by: hui1975 Change-Id: I3ed92c7f1c8b4b93df232ead211775e8706cc328 --- services/sensor/include/sensor_power_policy.h | 3 --- services/sensor/src/client_info.cpp | 2 +- services/sensor/src/sensor_power_policy.cpp | 9 ++++++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/services/sensor/include/sensor_power_policy.h b/services/sensor/include/sensor_power_policy.h index daf960d1..10eb4fab 100644 --- a/services/sensor/include/sensor_power_policy.h +++ b/services/sensor/include/sensor_power_policy.h @@ -44,9 +44,6 @@ private: std::unordered_map &SensorInfoMap); bool Resume(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); ErrCode RestoreSensorInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); - SensorHdiConnection &sensorHdiConnection_ = SensorHdiConnection::GetInstance(); - ClientInfo &clientInfo_ = ClientInfo::GetInstance(); - SensorManager &sensorManager_ = SensorManager::GetInstance(); std::mutex pidSensorInfoMutex_; std::unordered_map> pidSensorInfoMap_; }; diff --git a/services/sensor/src/client_info.cpp b/services/sensor/src/client_info.cpp index 754d4efc..a69bcbb4 100644 --- a/services/sensor/src/client_info.cpp +++ b/services/sensor/src/client_info.cpp @@ -698,7 +698,7 @@ int32_t ClientInfo::AddActiveInfoCBPid(int32_t pid) std::lock_guard activeInfoCBPidLock(activeInfoCBPidMutex_); auto pairRet = activeInfoCBPidSet_.insert(pid); if (!pairRet.second) { - SEN_HILOGE("ActiveInfoCBPidSet insert pid fail"); + SEN_HILOGE("Pid is duplicated"); return ERROR; } return ERR_OK; diff --git a/services/sensor/src/sensor_power_policy.cpp b/services/sensor/src/sensor_power_policy.cpp index cfe41444..ebdb6901 100644 --- a/services/sensor/src/sensor_power_policy.cpp +++ b/services/sensor/src/sensor_power_policy.cpp @@ -26,6 +26,9 @@ namespace { constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SensorPowerPolicy" }; constexpr int32_t INVALID_SENSOR_ID = -1; constexpr int64_t MAX_EVENT_COUNT = 1000; +ClientInfo &clientInfo_ = ClientInfo::GetInstance(); +SensorManager &sensorManager_ = SensorManager::GetInstance(); +SensorHdiConnection &sensorHdiConnection_ = SensorHdiConnection::GetInstance(); } // namespace bool SensorPowerPolicy::CheckFreezingSensor(int32_t sensorId) @@ -47,7 +50,7 @@ ErrCode SensorPowerPolicy::SuspendSensors(int32_t pid) SEN_HILOGI("Pid already call suspend, but some sensors suspend failed, suspend these sensors again"); std::unordered_map sensorInfoMap = pidSensorInfoIt->second; if (!Suspend(pid, sensorIdList, sensorInfoMap)) { - SEN_HILOGE("Some sensor suspend failed"); + SEN_HILOGE("Suspend last failed sensors, but some failed"); return DISABLE_SENSOR_ERR; } return ERR_OK; @@ -56,7 +59,7 @@ ErrCode SensorPowerPolicy::SuspendSensors(int32_t pid) auto isAllSuspend = Suspend(pid, sensorIdList, sensorInfoMap); pidSensorInfoMap_.insert(std::make_pair(pid, sensorInfoMap)); if (!isAllSuspend) { - SEN_HILOGE("Some sensor suspend failed"); + SEN_HILOGE("Suspend all sensors, but some failed"); return DISABLE_SENSOR_ERR; } return ERR_OK; @@ -69,7 +72,7 @@ bool SensorPowerPolicy::Suspend(int32_t pid, std::vector &sensorIdList, bool isAllSuspend = true; for (auto &sensorId : sensorIdList) { if (CheckFreezingSensor(sensorId)) { - SEN_HILOGD("Current sensor is pedometer detectio or pedometer, can not suspend"); + SEN_HILOGD("Current sensor is pedometer detection or pedometer, can not suspend"); continue; } auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); -- Gitee From 79f5db8f83c51fe74a1bdb7c8bc43e7537cba3cd Mon Sep 17 00:00:00 2001 From: hui1975 Date: Wed, 29 Mar 2023 03:42:41 +0000 Subject: [PATCH 31/53] update Signed-off-by: hui1975 Change-Id: I8ecadca4cedfa37b61f43910b2de6d470ebf087c --- services/sensor/src/client_info.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/sensor/src/client_info.cpp b/services/sensor/src/client_info.cpp index a69bcbb4..f37b2960 100644 --- a/services/sensor/src/client_info.cpp +++ b/services/sensor/src/client_info.cpp @@ -709,7 +709,7 @@ int32_t ClientInfo::DelActiveInfoCBPid(int32_t pid) std::lock_guard activeInfoCBPidLock(activeInfoCBPidMutex_); auto it = activeInfoCBPidSet_.find(pid); if (it == activeInfoCBPidSet_.end()) { - SEN_HILOGE("ActiveInfoCBPidSet not find pid"); + SEN_HILOGE("Pid is not exists"); return ERROR; } activeInfoCBPidSet_.erase(it); -- Gitee From 08a7e76e00ddf50b4a196f7fdfa101e987a854f2 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Thu, 6 Apr 2023 07:42:40 +0000 Subject: [PATCH 32/53] update Signed-off-by: hui1975 Change-Id: I65cb5411bf628fa1da5c58b9a1fdf2cd90a95bcb --- .../native/sensor/include/i_sensor_service.h | 4 +- .../sensor/include/sensor_service_proxy.h | 4 +- .../sensor/src/sensor_service_proxy.cpp | 4 +- interfaces/native/test/BUILD.gn | 6 +- interfaces/native/test/fuzztest/BUILD.gn | 9 ++- .../getsensoractiveinfos_fuzzer/BUILD.gn | 51 +++++++++++++++ .../getsensoractiveinfos_fuzzer/corpus/init | 14 +++++ .../getsensoractiveinfos_fuzzer.cpp | 63 +++++++++++++++++++ .../getsensoractiveinfos_fuzzer.h | 22 +++++++ .../getsensoractiveinfos_fuzzer/project.xml | 25 ++++++++ .../BUILD.gn | 51 +++++++++++++++ .../corpus/init | 14 +++++ .../project.xml | 25 ++++++++ .../registersensoractiveInfocb_fuzzer.cpp | 61 ++++++++++++++++++ .../registersensoractiveInfocb_fuzzer.h | 22 +++++++ .../fuzztest/resumesensors_fuzzer/BUILD.gn | 51 +++++++++++++++ .../fuzztest/resumesensors_fuzzer/corpus/init | 14 +++++ .../fuzztest/resumesensors_fuzzer/project.xml | 25 ++++++++ .../resumesensors_fuzzer.cpp | 60 ++++++++++++++++++ .../resumesensors_fuzzer.h | 22 +++++++ .../fuzztest/suspendsensors_fuzzer/BUILD.gn | 51 +++++++++++++++ .../suspendsensors_fuzzer/corpus/init | 14 +++++ .../suspendsensors_fuzzer/project.xml | 25 ++++++++ .../suspendsensors_fuzzer.cpp | 60 ++++++++++++++++++ .../suspendsensors_fuzzer.h | 22 +++++++ .../BUILD.gn | 51 +++++++++++++++ .../corpus/init | 14 +++++ .../project.xml | 25 ++++++++ .../unregistersensoractiveInfocb_fuzzer.cpp | 61 ++++++++++++++++++ .../unregistersensoractiveInfocb_fuzzer.h | 22 +++++++ .../test/unittest/sensor_power_test.cpp | 7 +-- services/sensor/include/sensor_service.h | 4 +- services/sensor/src/sensor_service.cpp | 4 +- 33 files changed, 887 insertions(+), 20 deletions(-) create mode 100644 interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/BUILD.gn create mode 100644 interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/corpus/init create mode 100644 interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.cpp create mode 100644 interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.h create mode 100644 interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/project.xml create mode 100644 interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/BUILD.gn create mode 100644 interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/corpus/init create mode 100644 interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/project.xml create mode 100644 interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.cpp create mode 100644 interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.h create mode 100644 interfaces/native/test/fuzztest/resumesensors_fuzzer/BUILD.gn create mode 100644 interfaces/native/test/fuzztest/resumesensors_fuzzer/corpus/init create mode 100644 interfaces/native/test/fuzztest/resumesensors_fuzzer/project.xml create mode 100644 interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.cpp create mode 100644 interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.h create mode 100644 interfaces/native/test/fuzztest/suspendsensors_fuzzer/BUILD.gn create mode 100644 interfaces/native/test/fuzztest/suspendsensors_fuzzer/corpus/init create mode 100644 interfaces/native/test/fuzztest/suspendsensors_fuzzer/project.xml create mode 100644 interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.cpp create mode 100644 interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.h create mode 100644 interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/BUILD.gn create mode 100644 interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/corpus/init create mode 100644 interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/project.xml create mode 100644 interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.cpp create mode 100644 interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.h diff --git a/frameworks/native/sensor/include/i_sensor_service.h b/frameworks/native/sensor/include/i_sensor_service.h index 26e28295..7404ad58 100755 --- a/frameworks/native/sensor/include/i_sensor_service.h +++ b/frameworks/native/sensor/include/i_sensor_service.h @@ -43,8 +43,8 @@ public: virtual ErrCode SuspendSensors(int32_t pid) = 0; virtual ErrCode ResumeSensors(int32_t pid) = 0; virtual ErrCode GetActiveInfoList(int32_t pid, std::vector &activeInfoList) = 0; - virtual ErrCode CreateSocketChannel(const sptr &sensorClient, int32_t &clientFd) = 0; - virtual ErrCode DestroySocketChannel(const sptr &sensorClient) = 0; + virtual ErrCode CreateSocketChannel(sptr sensorClient, int32_t &clientFd) = 0; + virtual ErrCode DestroySocketChannel(sptr sensorClient) = 0; virtual ErrCode EnableActiveInfoCB() = 0; virtual ErrCode DisableActiveInfoCB() = 0; enum { diff --git a/frameworks/native/sensor/include/sensor_service_proxy.h b/frameworks/native/sensor/include/sensor_service_proxy.h index b5fd2480..b652c538 100755 --- a/frameworks/native/sensor/include/sensor_service_proxy.h +++ b/frameworks/native/sensor/include/sensor_service_proxy.h @@ -38,8 +38,8 @@ public: ErrCode SuspendSensors(int32_t pid) override; ErrCode ResumeSensors(int32_t pid) override; ErrCode GetActiveInfoList(int32_t pid, std::vector &activeInfoList) override; - ErrCode CreateSocketChannel(const sptr &sensorClient, int32_t &clientFd) override; - ErrCode DestroySocketChannel(const sptr &sensorClient) override; + ErrCode CreateSocketChannel(sptr sensorClient, int32_t &clientFd) override; + ErrCode DestroySocketChannel(sptr sensorClient) override; ErrCode EnableActiveInfoCB() override; ErrCode DisableActiveInfoCB() override; diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 4651b120..4825c7e5 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -278,7 +278,7 @@ ErrCode SensorServiceProxy::GetActiveInfoList(int32_t pid, std::vector(ret); } -ErrCode SensorServiceProxy::CreateSocketChannel(const sptr &sensorClient, int32_t &clientFd) +ErrCode SensorServiceProxy::CreateSocketChannel(sptr sensorClient, int32_t &clientFd) { CHKPR(sensorClient, OBJECT_NULL); MessageParcel data; @@ -309,7 +309,7 @@ ErrCode SensorServiceProxy::CreateSocketChannel(const sptr &senso return static_cast(ret); } -ErrCode SensorServiceProxy::DestroySocketChannel(const sptr &sensorClient) +ErrCode SensorServiceProxy::DestroySocketChannel(sptr sensorClient) { CHKPR(sensorClient, OBJECT_NULL); MessageParcel data; diff --git a/interfaces/native/test/BUILD.gn b/interfaces/native/test/BUILD.gn index ea0d5c97..d61bae74 100644 --- a/interfaces/native/test/BUILD.gn +++ b/interfaces/native/test/BUILD.gn @@ -76,16 +76,12 @@ ohos_unittest("SensorAlgorithmTest") { ohos_unittest("SensorPowerTest") { module_out_path = module_output_path - sources = [ - "$SUBSYSTEM_DIR/sensor/test/unittest/common/src/system_info.cpp", - "unittest/sensor_power_test.cpp", - ] + sources = [ "unittest/sensor_power_test.cpp" ] include_dirs = [ "//commonlibrary/c_utils/base/include", "$SUBSYSTEM_DIR/sensor/utils/common/include", "$SUBSYSTEM_DIR/sensor/interfaces/native/include", - "$SUBSYSTEM_DIR/sensor/test/unittest/common/include", ] deps = [ diff --git a/interfaces/native/test/fuzztest/BUILD.gn b/interfaces/native/test/fuzztest/BUILD.gn index bd9265b3..f5165696 100644 --- a/interfaces/native/test/fuzztest/BUILD.gn +++ b/interfaces/native/test/fuzztest/BUILD.gn @@ -17,5 +17,12 @@ import("//build/test.gni") group("fuzztest") { testonly = true - deps = [ "sensoragent_fuzzer:fuzztest" ] + deps = [ + "sensoragent_fuzzer:fuzztest", + "suspendsensors_fuzzer:fuzztest", + "resumesensors_fuzzer:fuzztest", + "getsensoractiveinfos_fuzzer:fuzztest", + "registersensoractiveInfocb_fuzzer:fuzztest", + "unregistersensoractiveInfocb_fuzzer:fuzztest", + ] } diff --git a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/BUILD.gn b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/BUILD.gn new file mode 100644 index 00000000..71efd222 --- /dev/null +++ b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +module_output_path = "sensors/sensor" + +ohos_fuzztest("GetSensorActiveInfosFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "//base/sensors/sensor/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer" + + include_dirs = [ + "//base/sensors/sensor/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer", + "//base/sensors/sensor/interfaces/native/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "getsensoractiveinfos_fuzzer.cpp" ] + + deps = [ "//base/sensors/sensor/interfaces/native:sensor_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":GetSensorActiveInfosFuzzTest", + ] +} diff --git a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/corpus/init b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/corpus/init new file mode 100644 index 00000000..f8128231 --- /dev/null +++ b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.cpp b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.cpp new file mode 100644 index 00000000..a7ee7dd3 --- /dev/null +++ b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "getsensoractiveinfos_fuzzer.h" + +#include "securec.h" + +#include "sensor_agent.h" +#include "sensor_agent_type.h" + +namespace OHOS { +namespace Sensors { +namespace { +constexpr size_t DATA_MIN_SIZE = 4; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void GetSensorActiveInfosFuzzTest(const uint8_t* data, size_t size) +{ + if (data == nullptr || size < DATA_MIN_SIZE) { + return; + } + size_t startPos = 0; + int32_t pid {-1}; + GetObject(data + startPos, size - startPos, pid); + SensorActiveInfo *sensorActiveInfos {nullptr}; + int32_t count { 0 }; + GetSensorActiveInfos(pid, &sensorActiveInfos, &count); +} +} // Sensors +} // OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::Sensors::GetSensorActiveInfosFuzzTest(data, size); + return 0; +} + diff --git a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.h b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.h new file mode 100644 index 00000000..99e91497 --- /dev/null +++ b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "getsensoractiveinfos_fuzzer" + +#endif + diff --git a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/project.xml b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/project.xml new file mode 100644 index 00000000..20dc766d --- /dev/null +++ b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/BUILD.gn b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/BUILD.gn new file mode 100644 index 00000000..862c46b8 --- /dev/null +++ b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +module_output_path = "sensors/sensor" + +ohos_fuzztest("RegisterSensorActiveInfoCBFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "//base/sensors/sensor/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer" + + include_dirs = [ + "//base/sensors/sensor/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer", + "//base/sensors/sensor/interfaces/native/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "registersensoractiveInfocb_fuzzer.cpp" ] + + deps = [ "//base/sensors/sensor/interfaces/native:sensor_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":RegisterSensorActiveInfoCBFuzzTest", + ] +} diff --git a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/corpus/init b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/corpus/init new file mode 100644 index 00000000..f8128231 --- /dev/null +++ b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/project.xml b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/project.xml new file mode 100644 index 00000000..20dc766d --- /dev/null +++ b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.cpp b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.cpp new file mode 100644 index 00000000..dcab8db3 --- /dev/null +++ b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "registersensoractiveInfocb_fuzzer.h" + +#include "securec.h" + +#include "sensor_agent.h" +#include "sensor_agent_type.h" + +namespace OHOS { +namespace Sensors { +namespace { +constexpr size_t DATA_MIN_SIZE = 4; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void RegisterSensorActiveInfoCBFuzzTest(const uint8_t* data, size_t size) +{ + if (data == nullptr || size < DATA_MIN_SIZE) { + return; + } + size_t startPos = 0; + SensorActiveInfoCB callback = nullptr; + GetObject(data + startPos, size - startPos, callback); + RegisterSensorActiveInfoCB(callback); +} +} // Sensors +} // OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::Sensors::RegisterSensorActiveInfoCBFuzzTest(data, size); + return 0; +} + diff --git a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.h b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.h new file mode 100644 index 00000000..e5481f6f --- /dev/null +++ b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "registersensoractiveInfocb_fuzzer" + +#endif + diff --git a/interfaces/native/test/fuzztest/resumesensors_fuzzer/BUILD.gn b/interfaces/native/test/fuzztest/resumesensors_fuzzer/BUILD.gn new file mode 100644 index 00000000..65b0f4a8 --- /dev/null +++ b/interfaces/native/test/fuzztest/resumesensors_fuzzer/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +module_output_path = "sensors/sensor" + +ohos_fuzztest("ResumeSensorsFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "//base/sensors/sensor/interfaces/native/test/fuzztest/resumesensors_fuzzer" + + include_dirs = [ + "//base/sensors/sensor/interfaces/native/test/fuzztest/resumesensors_fuzzer", + "//base/sensors/sensor/interfaces/native/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "resumesensors_fuzzer.cpp" ] + + deps = [ "//base/sensors/sensor/interfaces/native:sensor_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":ResumeSensorsFuzzTest", + ] +} diff --git a/interfaces/native/test/fuzztest/resumesensors_fuzzer/corpus/init b/interfaces/native/test/fuzztest/resumesensors_fuzzer/corpus/init new file mode 100644 index 00000000..f8128231 --- /dev/null +++ b/interfaces/native/test/fuzztest/resumesensors_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/interfaces/native/test/fuzztest/resumesensors_fuzzer/project.xml b/interfaces/native/test/fuzztest/resumesensors_fuzzer/project.xml new file mode 100644 index 00000000..20dc766d --- /dev/null +++ b/interfaces/native/test/fuzztest/resumesensors_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.cpp b/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.cpp new file mode 100644 index 00000000..8c024ba4 --- /dev/null +++ b/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "resumesensors_fuzzer.h" + +#include "securec.h" + +#include "sensor_agent.h" + +namespace OHOS { +namespace Sensors { +namespace { +constexpr size_t DATA_MIN_SIZE = 4; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void ResumeSensorsFuzzTest(const uint8_t* data, size_t size) +{ + if (data == nullptr || size < DATA_MIN_SIZE) { + return; + } + size_t startPos = 0; + int32_t pid {-1}; + GetObject(data + startPos, size - startPos, pid); + ResumeSensors(pid); +} +} // Sensors +} // OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::Sensors::ResumeSensorsFuzzTest(data, size); + return 0; +} + diff --git a/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.h b/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.h new file mode 100644 index 00000000..97516a76 --- /dev/null +++ b/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "resumesensors_fuzzer" + +#endif + diff --git a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/BUILD.gn b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/BUILD.gn new file mode 100644 index 00000000..d20b18e4 --- /dev/null +++ b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +module_output_path = "sensors/sensor" + +ohos_fuzztest("SuspendSensorsFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "//base/sensors/sensor/interfaces/native/test/fuzztest/suspendsensors_fuzzer" + + include_dirs = [ + "//base/sensors/sensor/interfaces/native/test/fuzztest/suspendsensors_fuzzer", + "//base/sensors/sensor/interfaces/native/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "suspendsensors_fuzzer.cpp" ] + + deps = [ "//base/sensors/sensor/interfaces/native:sensor_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":SuspendSensorsFuzzTest", + ] +} diff --git a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/corpus/init b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/corpus/init new file mode 100644 index 00000000..f8128231 --- /dev/null +++ b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/project.xml b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/project.xml new file mode 100644 index 00000000..20dc766d --- /dev/null +++ b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.cpp b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.cpp new file mode 100644 index 00000000..60c60a53 --- /dev/null +++ b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "suspendsensors_fuzzer.h" + +#include "securec.h" + +#include "sensor_agent.h" + +namespace OHOS { +namespace Sensors { +namespace { +constexpr size_t DATA_MIN_SIZE = 4; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void SuspendSensorsFuzzTest(const uint8_t* data, size_t size) +{ + if (data == nullptr || size < DATA_MIN_SIZE) { + return; + } + size_t startPos = 0; + int32_t pid {-1}; + GetObject(data + startPos, size - startPos, pid); + SuspendSensors(pid); +} +} // Sensors +} // OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::Sensors::SuspendSensorsFuzzTest(data, size); + return 0; +} + diff --git a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.h b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.h new file mode 100644 index 00000000..11db9b6b --- /dev/null +++ b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "suspendsensors_fuzzer" + +#endif + diff --git a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/BUILD.gn b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/BUILD.gn new file mode 100644 index 00000000..23398fcf --- /dev/null +++ b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +module_output_path = "sensors/sensor" + +ohos_fuzztest("UnregisterSensorActiveInfoCBFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "//base/sensors/sensor/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer" + + include_dirs = [ + "//base/sensors/sensor/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer", + "//base/sensors/sensor/interfaces/native/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "unregistersensoractiveInfocb_fuzzer.cpp" ] + + deps = [ "//base/sensors/sensor/interfaces/native:sensor_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":UnregisterSensorActiveInfoCBFuzzTest", + ] +} diff --git a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/corpus/init b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/corpus/init new file mode 100644 index 00000000..f8128231 --- /dev/null +++ b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/project.xml b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/project.xml new file mode 100644 index 00000000..20dc766d --- /dev/null +++ b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.cpp b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.cpp new file mode 100644 index 00000000..c2d03be0 --- /dev/null +++ b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "unregistersensoractiveInfocb_fuzzer.h" + +#include "securec.h" + +#include "sensor_agent.h" +#include "sensor_agent_type.h" + +namespace OHOS { +namespace Sensors { +namespace { +constexpr size_t DATA_MIN_SIZE = 4; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void UnregisterSensorActiveInfoCBFuzzTest(const uint8_t* data, size_t size) +{ + if (data == nullptr || size < DATA_MIN_SIZE) { + return; + } + size_t startPos = 0; + SensorActiveInfoCB callback = nullptr; + GetObject(data + startPos, size - startPos, callback); + UnregisterSensorActiveInfoCB(callback); +} +} // Sensors +} // OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::Sensors::UnregisterSensorActiveInfoCBFuzzTest(data, size); + return 0; +} + diff --git a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.h b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.h new file mode 100644 index 00000000..380152c8 --- /dev/null +++ b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "unregistersensoractiveinfocb_fuzzer" + +#endif + diff --git a/interfaces/native/test/unittest/sensor_power_test.cpp b/interfaces/native/test/unittest/sensor_power_test.cpp index 2e1d2025..c0068e83 100644 --- a/interfaces/native/test/unittest/sensor_power_test.cpp +++ b/interfaces/native/test/unittest/sensor_power_test.cpp @@ -16,6 +16,8 @@ #include #include #include +#include +#include #include "accesstoken_kit.h" #include "nativetoken_kit.h" @@ -23,7 +25,6 @@ #include "sensor_agent.h" #include "sensors_errors.h" -#include "system_info.h" namespace OHOS { namespace Sensors { @@ -67,9 +68,7 @@ void SensorPowerTest::SetUpTestCase() AccessTokenKit::ReloadNativeTokenInfo(); delete[] perms; - SYSTEM_INFO::CpuInfo cpuInfo; - const std::string process_name = "SensorPowerTest"; - process_pid = cpuInfo.GetTaskPidFile(process_name); + process_pid = getpid(); SEN_HILOGI("Current process pid is %{public}d", process_pid); ASSERT_NE(process_pid, 0); } diff --git a/services/sensor/include/sensor_service.h b/services/sensor/include/sensor_service.h index 849c6dfc..dff3c41a 100644 --- a/services/sensor/include/sensor_service.h +++ b/services/sensor/include/sensor_service.h @@ -59,8 +59,8 @@ public: ErrCode SuspendSensors(int32_t pid) override; ErrCode ResumeSensors(int32_t pid) override; ErrCode GetActiveInfoList(int32_t pid, std::vector &activeInfoList) override; - ErrCode CreateSocketChannel(const sptr &sensorClient, int32_t &clientFd) override; - ErrCode DestroySocketChannel(const sptr &sensorClient) override; + ErrCode CreateSocketChannel(sptr sensorClient, int32_t &clientFd) override; + ErrCode DestroySocketChannel(sptr sensorClient) override; ErrCode EnableActiveInfoCB() override; ErrCode DisableActiveInfoCB() override; diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 2a7868ec..2fb69e69 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -456,7 +456,7 @@ ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector &a return ERR_OK; } -ErrCode SensorService::CreateSocketChannel(const sptr &sensorClient, int32_t &clientFd) +ErrCode SensorService::CreateSocketChannel(sptr sensorClient, int32_t &clientFd) { CALL_LOG_ENTER; int32_t serverFd = -1; @@ -471,7 +471,7 @@ ErrCode SensorService::CreateSocketChannel(const sptr &sensorClie return ERR_OK; } -ErrCode SensorService::DestroySocketChannel(const sptr &sensorClient) +ErrCode SensorService::DestroySocketChannel(sptr sensorClient) { CALL_LOG_ENTER; DelSession(GetCallingPid()); -- Gitee From 32bdfa0848eb846bfc8684b09c8a0820018ae009 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Tue, 11 Apr 2023 07:53:29 +0000 Subject: [PATCH 33/53] update Signed-off-by: hui1975 Change-Id: I78203b176e9ba8a45cf2da1ecbc3985f4e337c20 --- services/sensor/include/client_info.h | 2 +- services/sensor/include/sensor_power_policy.h | 4 ++-- services/sensor/include/stream_server.h | 4 ++-- services/sensor/src/client_info.cpp | 12 ++++++++---- services/sensor/src/sensor_power_policy.cpp | 6 ++++-- services/sensor/src/sensor_service.cpp | 6 +++--- services/sensor/src/stream_server.cpp | 4 ++-- 7 files changed, 22 insertions(+), 16 deletions(-) diff --git a/services/sensor/include/client_info.h b/services/sensor/include/client_info.h index 514ba48a..bf89eaaf 100644 --- a/services/sensor/include/client_info.h +++ b/services/sensor/include/client_info.h @@ -78,7 +78,7 @@ public: AccessTokenID GetTokenIdByPid(int32_t pid); int32_t AddActiveInfoCBPid(int32_t pid); int32_t DelActiveInfoCBPid(int32_t pid); - std::unordered_set GetActiveInfoCBPid(); + std::vector GetActiveInfoCBPid(); bool IsUnregisterClientDeathRecipient(int32_t pid); int32_t GetPidByTokenId(AccessTokenID tokenId); void UpdatePermState(int32_t pid, int32_t sensorId, bool state); diff --git a/services/sensor/include/sensor_power_policy.h b/services/sensor/include/sensor_power_policy.h index 10eb4fab..7416d3b8 100644 --- a/services/sensor/include/sensor_power_policy.h +++ b/services/sensor/include/sensor_power_policy.h @@ -35,8 +35,8 @@ class SensorPowerPolicy : public Singleton { public: ErrCode SuspendSensors(int32_t pid); ErrCode ResumeSensors(int32_t pid); - void GetActiveInfoList(int32_t pid, std::vector &activeInfoList); - void ReportActiveInfo(ActiveInfo activeInfo, const std::vector &sessionList); + std::vector GetActiveInfoList(int32_t pid); + void ReportActiveInfo(const ActiveInfo &activeInfo, const std::vector &sessionList); private: bool CheckFreezingSensor(int32_t sensorId); diff --git a/services/sensor/include/stream_server.h b/services/sensor/include/stream_server.h index 03e1ba7d..ee32c2da 100644 --- a/services/sensor/include/stream_server.h +++ b/services/sensor/include/stream_server.h @@ -28,8 +28,8 @@ class StreamServer : public StreamSocket { public: StreamServer() = default; virtual ~StreamServer(); - bool SendMsg(int32_t fd, NetPacket& pkt); - void Multicast(const std::vector& fdList, NetPacket& pkt); + bool SendMsg(int32_t fd, const NetPacket& pkt); + void Multicast(const std::vector& fdList, const NetPacket& pkt); int32_t GetClientFd(int32_t pid); int32_t GetClientPid(int32_t fd); SessionPtr GetSession(int32_t fd); diff --git a/services/sensor/src/client_info.cpp b/services/sensor/src/client_info.cpp index 604d80f6..495848bc 100644 --- a/services/sensor/src/client_info.cpp +++ b/services/sensor/src/client_info.cpp @@ -716,9 +716,13 @@ int32_t ClientInfo::DelActiveInfoCBPid(int32_t pid) return ERR_OK; } -std::unordered_set ClientInfo::GetActiveInfoCBPid() +std::vector ClientInfo::GetActiveInfoCBPid() { - return activeInfoCBPidSet_; + std::vector activeInfoCBPids; + for (auto it = activeInfoCBPidSet_.begin(); it != activeInfoCBPidSet_.end(); ++it) { + activeInfoCBPids.push_back(*it); + } + return activeInfoCBPids; } bool ClientInfo::IsUnregisterClientDeathRecipient(int32_t pid) @@ -726,15 +730,15 @@ bool ClientInfo::IsUnregisterClientDeathRecipient(int32_t pid) std::lock_guard channelLock(channelMutex_); auto channelIt = channelMap_.find(pid); if (channelIt != channelMap_.end()) { - SEN_HILOGD("Pid exist in channelMap"); return false; } + SEN_HILOGD("Pid is not exists in channelMap"); std::lock_guard activeInfoCBPidLock(activeInfoCBPidMutex_); auto pidIt = activeInfoCBPidSet_.find(pid); if (pidIt != activeInfoCBPidSet_.end()) { - SEN_HILOGD("Pid exist in activeInfoCBPidSet"); return false; } + SEN_HILOGD("Pid is not exists in activeInfoCBPidSet"); return true; } diff --git a/services/sensor/src/sensor_power_policy.cpp b/services/sensor/src/sensor_power_policy.cpp index ebdb6901..b466037f 100644 --- a/services/sensor/src/sensor_power_policy.cpp +++ b/services/sensor/src/sensor_power_policy.cpp @@ -173,9 +173,10 @@ ErrCode SensorPowerPolicy::RestoreSensorInfo(int32_t pid, int32_t sensorId, int6 return ERR_OK; } -void SensorPowerPolicy::GetActiveInfoList(int32_t pid, std::vector &activeInfoList) +std::vector SensorPowerPolicy::GetActiveInfoList(int32_t pid) { CALL_LOG_ENTER; + std::vector activeInfoList; std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); for (auto &sensorId : sensorIdList) { auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); @@ -183,9 +184,10 @@ void SensorPowerPolicy::GetActiveInfoList(int32_t pid, std::vector & sensorInfo.GetMaxReportDelayNs()); activeInfoList.push_back(activeInfo); } + return activeInfoList; } -void SensorPowerPolicy::ReportActiveInfo(ActiveInfo activeInfo, +void SensorPowerPolicy::ReportActiveInfo(const ActiveInfo &activeInfo, const std::vector &sessionList) { CALL_LOG_ENTER; diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 2fb69e69..e83f7f0d 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -452,7 +452,7 @@ ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector &a SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } - sensorPowerPolicy_.GetActiveInfoList(pid, activeInfoList); + activeInfoList = sensorPowerPolicy_.GetActiveInfoList(pid); return ERR_OK; } @@ -497,8 +497,8 @@ void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid) { CALL_LOG_ENTER; std::vector sessionList; - auto pidSet = clientInfo_.GetActiveInfoCBPid(); - for (auto pid : pidSet) { + auto pidList = clientInfo_.GetActiveInfoCBPid(); + for (auto pid : pidList) { auto sess = GetSessionByPid(pid); if (sess != nullptr) { sessionList.push_back(sess); diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index ed7d02a5..475ee02e 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -40,7 +40,7 @@ StreamServer::~StreamServer() sessionsMap_.clear(); } -bool StreamServer::SendMsg(int32_t fd, NetPacket& pkt) +bool StreamServer::SendMsg(int32_t fd, const NetPacket& pkt) { CALL_LOG_ENTER; if (fd < 0) { @@ -55,7 +55,7 @@ bool StreamServer::SendMsg(int32_t fd, NetPacket& pkt) return ses->SendMsg(pkt); } -void StreamServer::Multicast(const std::vector& fdList, NetPacket& pkt) +void StreamServer::Multicast(const std::vector& fdList, const NetPacket& pkt) { CALL_LOG_ENTER; for (const auto &item : fdList) { -- Gitee From 411a9fb39137158256ac353c74434c7ce509b5c5 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Tue, 11 Apr 2023 11:04:17 +0000 Subject: [PATCH 34/53] update Signed-off-by: hui1975 Change-Id: Ib992f4b85e4c63316cfc8acbdc5118c0e9c46e59 --- utils/ipc/include/stream_session.h | 2 +- utils/ipc/src/stream_session.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/utils/ipc/include/stream_session.h b/utils/ipc/include/stream_session.h index 46f5d430..55a991e9 100644 --- a/utils/ipc/include/stream_session.h +++ b/utils/ipc/include/stream_session.h @@ -39,7 +39,7 @@ public: StreamSession(const std::string &programName, const int32_t fd, const int32_t uid, const int32_t pid); ~StreamSession() = default; bool SendMsg(const char *buf, size_t size) const; - bool SendMsg(NetPacket &pkt) const; + bool SendMsg(const NetPacket &pkt) const; void Close(); int32_t GetUid() const; int32_t GetPid() const; diff --git a/utils/ipc/src/stream_session.cpp b/utils/ipc/src/stream_session.cpp index 10abaa09..a53fd9cf 100644 --- a/utils/ipc/src/stream_session.cpp +++ b/utils/ipc/src/stream_session.cpp @@ -104,7 +104,7 @@ void StreamSession::UpdateDescript() descript_ = oss.str().c_str(); } -bool StreamSession::SendMsg(NetPacket &pkt) const +bool StreamSession::SendMsg(const NetPacket &pkt) const { if (pkt.ChkRWError()) { SEN_HILOGE("Read and write status failed"); -- Gitee From 6ec4f50a13c192932c029f25bc4a8dac1ff5ffec Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 17 Apr 2023 07:44:50 +0000 Subject: [PATCH 35/53] update Signed-off-by: hui1975 Change-Id: I483ef7abc61b01ce7c2defe7f6b58f672682eec6 --- utils/ipc/src/stream_buffer.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/utils/ipc/src/stream_buffer.cpp b/utils/ipc/src/stream_buffer.cpp index 6b9fe1de..e666585c 100644 --- a/utils/ipc/src/stream_buffer.cpp +++ b/utils/ipc/src/stream_buffer.cpp @@ -15,9 +15,6 @@ #include "stream_buffer.h" -#include -#include - namespace OHOS { namespace Sensors { StreamBuffer::StreamBuffer(const StreamBuffer &buf) -- Gitee From 3ad2431009eef6f5fd35c9e7806ef00124c3b47a Mon Sep 17 00:00:00 2001 From: hui1975 Date: Tue, 18 Apr 2023 02:59:06 +0000 Subject: [PATCH 36/53] update Signed-off-by: hui1975 Change-Id: I3e57cb592eb54a78acf4aed7997a07242af34621 --- services/sensor/src/stream_server.cpp | 33 ++++++++------------------- 1 file changed, 9 insertions(+), 24 deletions(-) diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index 475ee02e..ab59a8d3 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -18,18 +18,16 @@ #include #include -#include "accesstoken_kit.h" - #include "sensors_errors.h" namespace OHOS { namespace Sensors { namespace { -using namespace Security::AccessToken; constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "StreamServer" }; constexpr int32_t INVALID_PID = -1; constexpr int32_t INVALID_FD = -1; } // namespace + StreamServer::~StreamServer() { CALL_LOG_ENTER; @@ -109,7 +107,6 @@ int32_t StreamServer::AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenT int32_t &serverFd, int32_t &clientFd) { CALL_LOG_ENTER; - std::string programName = ""; int32_t sockFds[2] = { -1 }; if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockFds) != 0) { SEN_HILOGE("Call socketpair failed, errno:%{public}d", errno); @@ -122,7 +119,6 @@ int32_t StreamServer::AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenT return ERROR; } static constexpr size_t bufferSize = 32 * 1024; - static constexpr size_t nativeBufferSize = 64 * 1024; SessionPtr sess = nullptr; if (setsockopt(serverFd, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)) != 0) { SEN_HILOGE("Setsockopt serverFd failed, errno: %{public}d", errno); @@ -132,26 +128,15 @@ int32_t StreamServer::AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenT SEN_HILOGE("Setsockopt serverFd failed, errno: %{public}d", errno); goto CLOSE_SOCK; } - if (tokenType == ATokenTypeEnum::TOKEN_NATIVE) { - if (setsockopt(clientFd, SOL_SOCKET, SO_SNDBUF, &nativeBufferSize, sizeof(nativeBufferSize)) != 0) { - SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); - goto CLOSE_SOCK; - } - if (setsockopt(clientFd, SOL_SOCKET, SO_RCVBUF, &nativeBufferSize, sizeof(nativeBufferSize)) != 0) { - SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); - goto CLOSE_SOCK; - } - } else { - if (setsockopt(clientFd, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); - goto CLOSE_SOCK; - } - if (setsockopt(clientFd, SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); - goto CLOSE_SOCK; - } + if (setsockopt(clientFd, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)) != 0) { + SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); + goto CLOSE_SOCK; + } + if (setsockopt(clientFd, SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize)) != 0) { + SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); + goto CLOSE_SOCK; } - sess = std::make_shared(programName, serverFd, uid, pid); + sess = std::make_shared("", serverFd, uid, pid); sess->SetTokenType(tokenType); if (!AddSession(sess)) { SEN_HILOGE("AddSession fail"); -- Gitee From 95fa7b70d035b577ea2c4101e4fea5ef1f1d880c Mon Sep 17 00:00:00 2001 From: hui1975 Date: Tue, 18 Apr 2023 09:46:01 +0000 Subject: [PATCH 37/53] update Signed-off-by: hui1975 Change-Id: I7f3bb3ba47ffc1bb282e6f0b99a512aa0799121e --- frameworks/native/sensor/src/sensor_service_proxy.cpp | 5 ----- services/sensor/src/flush_info_record.cpp | 5 ----- services/sensor/src/sensor_service.cpp | 5 ----- 3 files changed, 15 deletions(-) diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 4825c7e5..424759a8 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -29,11 +29,6 @@ using namespace OHOS::HiviewDFX; namespace { constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SensorServiceProxy" }; constexpr int32_t MAX_SENSOR_COUNT = 200; -enum { - FLUSH = 0, - SET_MODE, - RESERVED, -}; } // namespace SensorServiceProxy::SensorServiceProxy(const sptr &impl) : IRemoteProxy(impl) diff --git a/services/sensor/src/flush_info_record.cpp b/services/sensor/src/flush_info_record.cpp index ec19f8f9..4953bb12 100644 --- a/services/sensor/src/flush_info_record.cpp +++ b/services/sensor/src/flush_info_record.cpp @@ -24,11 +24,6 @@ using namespace OHOS::HiviewDFX; namespace { constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "FlushInfoRecord" }; constexpr int32_t CHANNEL_NO_FLUSH = -1; -enum { - FLUSH = 0, - SET_MODE, - RESERVED, -}; } // namespace std::unordered_map> FlushInfoRecord::GetFlushInfo() diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index e83f7f0d..8d65fce2 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -40,11 +40,6 @@ constexpr int32_t INVALID_SENSOR_ID = -1; constexpr int32_t INVALID_PID = -1; constexpr int64_t MAX_EVENT_COUNT = 1000; std::atomic_bool g_isRegister = false; -enum { - FLUSH = 0, - SET_MODE, - RESERVED, -}; } // namespace REGISTER_SYSTEM_ABILITY_BY_ID(SensorService, SENSOR_SERVICE_ABILITY_ID, true); -- Gitee From ec443e61708ecee63e4eb751dad18caeef74cf70 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Thu, 20 Apr 2023 11:48:53 +0000 Subject: [PATCH 38/53] update Signed-off-by: hui1975 Change-Id: I47643f9206151a6f12f6517e5ef6f309677922f9 --- .../sensor/src/sensor_service_proxy.cpp | 38 +++++++++---------- services/sensor/include/client_info.h | 2 +- services/sensor/include/stream_server.h | 3 +- services/sensor/src/client_info.cpp | 2 +- services/sensor/src/sensor_service.cpp | 8 ++-- services/sensor/src/sensor_service_stub.cpp | 35 +++++++++-------- services/sensor/src/stream_server.cpp | 10 ++--- 7 files changed, 51 insertions(+), 47 deletions(-) diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 424759a8..3491dcda 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -190,11 +190,11 @@ ErrCode SensorServiceProxy::SuspendSensors(int32_t pid) { MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { - SEN_HILOGE("Write descriptor failed"); + SEN_HILOGE("Parcel write descriptor failed"); return WRITE_PARCEL_ERR; } if (!data.WriteInt32(pid)) { - SEN_HILOGE("Write pid failed"); + SEN_HILOGE("Parcel write pid failed"); return WRITE_PARCEL_ERR; } sptr remote = Remote(); @@ -214,11 +214,11 @@ ErrCode SensorServiceProxy::ResumeSensors(int32_t pid) { MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { - SEN_HILOGE("Write descriptor failed"); + SEN_HILOGE("Parcel write descriptor failed"); return WRITE_PARCEL_ERR; } if (!data.WriteInt32(pid)) { - SEN_HILOGE("Write pid failed"); + SEN_HILOGE("Parcel write pid failed"); return WRITE_PARCEL_ERR; } sptr remote = Remote(); @@ -238,11 +238,11 @@ ErrCode SensorServiceProxy::GetActiveInfoList(int32_t pid, std::vector remote = Remote(); @@ -256,16 +256,16 @@ ErrCode SensorServiceProxy::GetActiveInfoList(int32_t pid, std::vector(ret); } - int32_t activeInfoCount; - if (!reply.ReadInt32(activeInfoCount)) { + size_t activeInfoCount; + if (!reply.ReadUint32(activeInfoCount)) { SEN_HILOGE("Parcel read activeInfoCount failed"); return READ_PARCEL_ERR; } ActiveInfo activeInfo; - for (int32_t i = 0; i < activeInfoCount; ++i) { + for (size_t i = 0; i < activeInfoCount; ++i) { auto tmpActiveInfo = activeInfo.Unmarshalling(reply); if (tmpActiveInfo == nullptr) { - SEN_HILOGE("Current activeInfo is nullptr, i:%{public}d", i); + SEN_HILOGE("Current activeInfo is nullptr, i:%{public}zu", i); continue; } activeInfoList.push_back(*tmpActiveInfo); @@ -275,14 +275,14 @@ ErrCode SensorServiceProxy::GetActiveInfoList(int32_t pid, std::vector sensorClient, int32_t &clientFd) { - CHKPR(sensorClient, OBJECT_NULL); + CHKPR(sensorClient, INVALID_POINTER); MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { - SEN_HILOGE("Write descriptor failed"); + SEN_HILOGE("Parcel write descriptor failed"); return WRITE_PARCEL_ERR; } if (!data.WriteRemoteObject(sensorClient)) { - SEN_HILOGE("Write sensorClient failed"); + SEN_HILOGE("Parcel write sensorClient failed"); return WRITE_PARCEL_ERR; } MessageParcel reply; @@ -298,7 +298,7 @@ ErrCode SensorServiceProxy::CreateSocketChannel(sptr sensorClient } clientFd = reply.ReadFileDescriptor(); if (clientFd < 0) { - SEN_HILOGE("Read file descriptor failed"); + SEN_HILOGE("Invalid fd"); return ERROR; } return static_cast(ret); @@ -306,14 +306,14 @@ ErrCode SensorServiceProxy::CreateSocketChannel(sptr sensorClient ErrCode SensorServiceProxy::DestroySocketChannel(sptr sensorClient) { - CHKPR(sensorClient, OBJECT_NULL); + CHKPR(sensorClient, INVALID_POINTER); MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { - SEN_HILOGE("write descriptor failed"); + SEN_HILOGE("Parcel write descriptor failed"); return WRITE_PARCEL_ERR; } if (!data.WriteRemoteObject(sensorClient)) { - SEN_HILOGE("Write sensorClient failed"); + SEN_HILOGE("Parcel write sensorClient failed"); return WRITE_PARCEL_ERR; } sptr remote = Remote(); @@ -333,7 +333,7 @@ ErrCode SensorServiceProxy::EnableActiveInfoCB() { MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { - SEN_HILOGE("write descriptor failed"); + SEN_HILOGE("Parcel write descriptor failed"); return WRITE_PARCEL_ERR; } sptr remote = Remote(); @@ -353,7 +353,7 @@ ErrCode SensorServiceProxy::DisableActiveInfoCB() { MessageParcel data; if (!data.WriteInterfaceToken(SensorServiceProxy::GetDescriptor())) { - SEN_HILOGE("write descriptor failed"); + SEN_HILOGE("Parcel write descriptor failed"); return WRITE_PARCEL_ERR; } sptr remote = Remote(); diff --git a/services/sensor/include/client_info.h b/services/sensor/include/client_info.h index bf89eaaf..c6c020e3 100644 --- a/services/sensor/include/client_info.h +++ b/services/sensor/include/client_info.h @@ -79,7 +79,7 @@ public: int32_t AddActiveInfoCBPid(int32_t pid); int32_t DelActiveInfoCBPid(int32_t pid); std::vector GetActiveInfoCBPid(); - bool IsUnregisterClientDeathRecipient(int32_t pid); + bool CallingService(int32_t pid); int32_t GetPidByTokenId(AccessTokenID tokenId); void UpdatePermState(int32_t pid, int32_t sensorId, bool state); void ChangeSensorPerm(AccessTokenID tokenId, const std::string &permName, bool state); diff --git a/services/sensor/include/stream_server.h b/services/sensor/include/stream_server.h index ee32c2da..05b1a8b7 100644 --- a/services/sensor/include/stream_server.h +++ b/services/sensor/include/stream_server.h @@ -39,9 +39,8 @@ public: protected: bool AddSession(SessionPtr ses); void DelSession(int32_t pid); - std::mutex idxPidMutex_; - std::map idxPidMap_; std::mutex sessionMutex_; + std::map idxPidMap_; std::map sessionsMap_; }; } // namespace Sensors diff --git a/services/sensor/src/client_info.cpp b/services/sensor/src/client_info.cpp index 495848bc..d02a3a26 100644 --- a/services/sensor/src/client_info.cpp +++ b/services/sensor/src/client_info.cpp @@ -725,7 +725,7 @@ std::vector ClientInfo::GetActiveInfoCBPid() return activeInfoCBPids; } -bool ClientInfo::IsUnregisterClientDeathRecipient(int32_t pid) +bool ClientInfo::CallingService(int32_t pid) { std::lock_guard channelLock(channelMutex_); auto channelIt = channelMap_.find(pid); diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 8d65fce2..e63a6440 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -386,8 +386,8 @@ void SensorService::UnregisterClientDeathRecipient(sptr sensorCli SEN_HILOGE("Pid is invalid"); return; } - if (!clientInfo_.IsUnregisterClientDeathRecipient(pid)) { - SEN_HILOGD("Client call other service, can not unregister client death recipient"); + if (!clientInfo_.CallingService(pid)) { + SEN_HILOGD("Cannot unregister client death recipient"); return; } sptr client = iface_cast(sensorClient); @@ -454,6 +454,7 @@ ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector &a ErrCode SensorService::CreateSocketChannel(sptr sensorClient, int32_t &clientFd) { CALL_LOG_ENTER; + CHKPR(sensorClient, INVALID_POINTER); int32_t serverFd = -1; int32_t ret = AddSocketPairInfo(GetCallingUid(), GetCallingPid(), AccessTokenKit::GetTokenTypeFlag(GetCallingTokenID()), @@ -469,6 +470,7 @@ ErrCode SensorService::CreateSocketChannel(sptr sensorClient, int ErrCode SensorService::DestroySocketChannel(sptr sensorClient) { CALL_LOG_ENTER; + CHKPR(sensorClient, INVALID_POINTER); DelSession(GetCallingPid()); UnregisterClientDeathRecipient(sensorClient); return ERR_OK; @@ -493,7 +495,7 @@ void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid) CALL_LOG_ENTER; std::vector sessionList; auto pidList = clientInfo_.GetActiveInfoCBPid(); - for (auto pid : pidList) { + for (const auto &pid : pidList) { auto sess = GetSessionByPid(pid); if (sess != nullptr) { sessionList.push_back(sess); diff --git a/services/sensor/src/sensor_service_stub.cpp b/services/sensor/src/sensor_service_stub.cpp index 699bf1e6..42d877cf 100755 --- a/services/sensor/src/sensor_service_stub.cpp +++ b/services/sensor/src/sensor_service_stub.cpp @@ -170,8 +170,8 @@ ErrCode SensorServiceStub::SuspendSensorsInner(MessageParcel &data, MessageParce (void)reply; int32_t pid; if (!data.ReadInt32(pid)) { - SEN_HILOGE("Parcel read failed"); - return ERROR; + SEN_HILOGE("Parcel read pid failed"); + return READ_PARCEL_ERR; } return SuspendSensors(pid); } @@ -186,8 +186,8 @@ ErrCode SensorServiceStub::ResumeSensorsInner(MessageParcel &data, MessageParcel (void)reply; int32_t pid; if (!data.ReadInt32(pid)) { - SEN_HILOGE("Parcel read failed"); - return ERROR; + SEN_HILOGE("Parcel read pid failed"); + return READ_PARCEL_ERR; } return ResumeSensors(pid); } @@ -201,8 +201,8 @@ ErrCode SensorServiceStub::GetActiveInfoListInner(MessageParcel &data, MessagePa } int32_t pid; if (!data.ReadInt32(pid)) { - SEN_HILOGE("Parcel read failed"); - return ERROR; + SEN_HILOGE("Parcel read pid failed"); + return READ_PARCEL_ERR; } std::vector activeInfoList; int32_t ret = GetActiveInfoList(pid, activeInfoList); @@ -210,12 +210,15 @@ ErrCode SensorServiceStub::GetActiveInfoListInner(MessageParcel &data, MessagePa SEN_HILOGE("Get activeInfo list failed"); return ret; } - int32_t activeInfoCount = int32_t { activeInfoList.size() }; - reply.WriteInt32(activeInfoCount); - for (int32_t i = 0; i < activeInfoCount; i++) { + size_t activeInfoCount = activeInfoList.size(); + if (!reply.WriteUint32(activeInfoCount)) { + SEN_HILOGE("Parcel write activeInfoCount failed"); + return WRITE_PARCEL_ERR; + } + for (size_t i = 0; i < activeInfoCount; i++) { if (!activeInfoList[i].Marshalling(reply)) { - SEN_HILOGE("ActiveInfo %{public}d failed", i); - return ERROR; + SEN_HILOGE("ActiveInfo %{public}zu marshalling failed", i); + return WRITE_PARCEL_ERR; } } return ERR_OK; @@ -224,7 +227,7 @@ ErrCode SensorServiceStub::GetActiveInfoListInner(MessageParcel &data, MessagePa ErrCode SensorServiceStub::CreateSocketChannelInner(MessageParcel &data, MessageParcel &reply) { sptr sensorClient = data.ReadRemoteObject(); - CHKPR(sensorClient, OBJECT_NULL); + CHKPR(sensorClient, INVALID_POINTER); int32_t clientFd = -1; int32_t ret = CreateSocketChannel(sensorClient, clientFd); if (ret != ERR_OK) { @@ -232,9 +235,9 @@ ErrCode SensorServiceStub::CreateSocketChannelInner(MessageParcel &data, Message return ret; } if (!reply.WriteFileDescriptor(clientFd)) { - SEN_HILOGE("Write file descriptor failed"); + SEN_HILOGE("Parcel write file descriptor failed"); close(clientFd); - return ERROR; + return WRITE_PARCEL_ERR; } close(clientFd); return ERR_OK; @@ -243,10 +246,10 @@ ErrCode SensorServiceStub::CreateSocketChannelInner(MessageParcel &data, Message ErrCode SensorServiceStub::DestroySocketChannelInner(MessageParcel &data, MessageParcel &reply) { sptr sensorClient = data.ReadRemoteObject(); - CHKPR(sensorClient, OBJECT_NULL); + CHKPR(sensorClient, INVALID_POINTER); int32_t ret = DestroySocketChannel(sensorClient); if (ret != ERR_OK) { - SEN_HILOGE("DestroySocketChannel failed"); + SEN_HILOGE("Destroy socket channel failed"); return ret; } return ERR_OK; diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index ab59a8d3..ec9a7efa 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -16,6 +16,7 @@ #include "stream_server.h" #include + #include #include "sensors_errors.h" @@ -31,6 +32,7 @@ constexpr int32_t INVALID_FD = -1; StreamServer::~StreamServer() { CALL_LOG_ENTER; + std::lock_guard sessionLock(sessionMutex_); idxPidMap_.clear(); for (const auto &item : sessionsMap_) { item.second->Close(); @@ -63,7 +65,7 @@ void StreamServer::Multicast(const std::vector& fdList, const NetPacket int32_t StreamServer::GetClientFd(int32_t pid) { - std::lock_guard idxPidLock(idxPidMutex_); + std::lock_guard sessionLock(sessionMutex_); auto it = idxPidMap_.find(pid); if (it == idxPidMap_.end()) { return INVALID_FD; @@ -172,9 +174,8 @@ bool StreamServer::AddSession(SessionPtr ses) return false; } DelSession(pid); - std::lock_guard idxPidLock(idxPidMutex_); - idxPidMap_[pid] = fd; std::lock_guard sessionLock(sessionMutex_); + idxPidMap_[pid] = fd; sessionsMap_[fd] = ses; return true; } @@ -182,14 +183,13 @@ bool StreamServer::AddSession(SessionPtr ses) void StreamServer::DelSession(int32_t pid) { CALL_LOG_ENTER; - std::lock_guard idxPidLock(idxPidMutex_); + std::lock_guard sessionLock(sessionMutex_); auto pidIt = idxPidMap_.find(pid); if (pidIt == idxPidMap_.end()) { return; } int32_t fd = pidIt->second; idxPidMap_.erase(pidIt); - std::lock_guard sessionLock(sessionMutex_); auto fdIt = sessionsMap_.find(fd); if (fdIt != sessionsMap_.end()) { sessionsMap_.erase(fdIt); -- Gitee From cf70eb62bbdbb3a0ba500d841628c0bd410b6bbf Mon Sep 17 00:00:00 2001 From: hui1975 Date: Thu, 20 Apr 2023 12:48:17 +0000 Subject: [PATCH 39/53] update Signed-off-by: hui1975 Change-Id: I0d6295183bd814d3f563f27c8feb191838f69234 --- services/sensor/src/sensor_service.cpp | 4 +--- services/sensor/src/sensor_service_stub.cpp | 10 +++++----- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index e63a6440..b125383c 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -20,7 +20,6 @@ #include #include -#include "accesstoken_kit.h" #include "hisysevent.h" #include "iservice_registry.h" #include "permission_util.h" @@ -33,7 +32,6 @@ namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; -using namespace Security::AccessToken; namespace { constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SensorService" }; constexpr int32_t INVALID_SENSOR_ID = -1; @@ -457,7 +455,7 @@ ErrCode SensorService::CreateSocketChannel(sptr sensorClient, int CHKPR(sensorClient, INVALID_POINTER); int32_t serverFd = -1; int32_t ret = AddSocketPairInfo(GetCallingUid(), GetCallingPid(), - AccessTokenKit::GetTokenTypeFlag(GetCallingTokenID()), + AccessTokenKit::GetTokenTypeFlag(GetCallingTokenID()), serverFd, std::ref(clientFd)); if (ret != ERR_OK) { SEN_HILOGE("Add socket pair info failed, ret:%{public}d", ret); diff --git a/services/sensor/src/sensor_service_stub.cpp b/services/sensor/src/sensor_service_stub.cpp index 42d877cf..b3b00c2a 100755 --- a/services/sensor/src/sensor_service_stub.cpp +++ b/services/sensor/src/sensor_service_stub.cpp @@ -163,7 +163,7 @@ ErrCode SensorServiceStub::DestroyDataChannelInner(MessageParcel &data, MessageP ErrCode SensorServiceStub::SuspendSensorsInner(MessageParcel &data, MessageParcel &reply) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); - if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { + if (!permissionUtil.IsNativeToken(GetCallingTokenID())) { SEN_HILOGE("TokenType is not TOKEN_NATIVE"); return PERMISSION_DENIED; } @@ -179,7 +179,7 @@ ErrCode SensorServiceStub::SuspendSensorsInner(MessageParcel &data, MessageParce ErrCode SensorServiceStub::ResumeSensorsInner(MessageParcel &data, MessageParcel &reply) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); - if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { + if (!permissionUtil.IsNativeToken(GetCallingTokenID())) { SEN_HILOGE("TokenType is not TOKEN_NATIVE"); return PERMISSION_DENIED; } @@ -195,7 +195,7 @@ ErrCode SensorServiceStub::ResumeSensorsInner(MessageParcel &data, MessageParcel ErrCode SensorServiceStub::GetActiveInfoListInner(MessageParcel &data, MessageParcel &reply) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); - if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { + if (!permissionUtil.IsNativeToken(GetCallingTokenID())) { SEN_HILOGE("TokenType is not TOKEN_NATIVE"); return PERMISSION_DENIED; } @@ -258,7 +258,7 @@ ErrCode SensorServiceStub::DestroySocketChannelInner(MessageParcel &data, Messag ErrCode SensorServiceStub::EnableActiveInfoCBInner(MessageParcel &data, MessageParcel &reply) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); - if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { + if (!permissionUtil.IsNativeToken(GetCallingTokenID())) { SEN_HILOGE("TokenType is not TOKEN_NATIVE"); return PERMISSION_DENIED; } @@ -268,7 +268,7 @@ ErrCode SensorServiceStub::EnableActiveInfoCBInner(MessageParcel &data, MessageP ErrCode SensorServiceStub::DisableActiveInfoCBInner(MessageParcel &data, MessageParcel &reply) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); - if(!permissionUtil.IsNativeToken(GetCallingTokenID())) { + if (!permissionUtil.IsNativeToken(GetCallingTokenID())) { SEN_HILOGE("TokenType is not TOKEN_NATIVE"); return PERMISSION_DENIED; } -- Gitee From 2f26104b9eb48ec4fee606ed94e006a80ef265af Mon Sep 17 00:00:00 2001 From: hui1975 Date: Fri, 21 Apr 2023 07:40:18 +0000 Subject: [PATCH 40/53] update Signed-off-by: hui1975 Change-Id: I5ab744532afe55a75ffd5d5f1e155f700630d880 --- .../sensor/src/sensor_service_proxy.cpp | 60 ++----- services/sensor/src/sensor_service_stub.cpp | 56 ++---- services/sensor/src/stream_server.cpp | 12 +- utils/common/include/sensor_parcel.h | 160 ++++++++++++++++++ utils/common/src/sensor.cpp | 4 +- 5 files changed, 195 insertions(+), 97 deletions(-) create mode 100644 utils/common/include/sensor_parcel.h diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 3491dcda..3f8ac241 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -43,18 +43,9 @@ ErrCode SensorServiceProxy::EnableSensor(int32_t sensorId, int64_t samplingPerio SEN_HILOGE("write descriptor failed"); return WRITE_PARCEL_ERR; } - if (!data.WriteInt32(sensorId)) { - SEN_HILOGE("write sensorId failed"); - return WRITE_PARCEL_ERR; - } - if (!data.WriteInt64(samplingPeriodNs)) { - SEN_HILOGE("write samplingPeriodNs failed"); - return WRITE_PARCEL_ERR; - } - if (!data.WriteInt64(maxReportDelayNs)) { - SEN_HILOGE("write maxReportDelayNs failed"); - return WRITE_PARCEL_ERR; - } + WRITEINT32(data, sensorId, WRITE_PARCEL_ERR); + WRITEINT64(data, samplingPeriodNs, WRITE_PARCEL_ERR); + WRITEINT64(data, maxReportDelayNs, WRITE_PARCEL_ERR); sptr remote = Remote(); CHKPR(remote, ERROR); int32_t ret = remote->SendRequest(ISensorService::ENABLE_SENSOR, data, reply, option); @@ -75,10 +66,7 @@ ErrCode SensorServiceProxy::DisableSensor(int32_t sensorId) SEN_HILOGE("write descriptor failed"); return WRITE_PARCEL_ERR; } - if (!data.WriteInt32(sensorId)) { - SEN_HILOGE("write sensorId failed"); - return WRITE_PARCEL_ERR; - } + WRITEINT32(data, sensorId, WRITE_PARCEL_ERR); sptr remote = Remote(); CHKPR(remote, ERROR); int32_t ret = remote->SendRequest(ISensorService::DISABLE_SENSOR, data, reply, option); @@ -145,10 +133,7 @@ ErrCode SensorServiceProxy::TransferDataChannel(const sptrSendToBinder(data); - if (!data.WriteRemoteObject(sensorClient)) { - SEN_HILOGE("sensorClient failed"); - return WRITE_PARCEL_ERR; - } + WRITEREMOTEOBJECT(data, sensorClient, WRITE_PARCEL_ERR); sptr remote = Remote(); CHKPR(remote, ERROR); int32_t ret = remote->SendRequest(ISensorService::TRANSFER_DATA_CHANNEL, data, reply, option); @@ -171,10 +156,7 @@ ErrCode SensorServiceProxy::DestroySensorChannel(sptr sensorClien SEN_HILOGE("write descriptor failed"); return WRITE_PARCEL_ERR; } - if (!data.WriteRemoteObject(sensorClient)) { - SEN_HILOGE("write sensorClient failed"); - return WRITE_PARCEL_ERR; - } + WRITEREMOTEOBJECT(data, sensorClient, WRITE_PARCEL_ERR); sptr remote = Remote(); CHKPR(remote, ERROR); int32_t ret = remote->SendRequest(ISensorService::DESTROY_SENSOR_CHANNEL, data, reply, option); @@ -193,10 +175,7 @@ ErrCode SensorServiceProxy::SuspendSensors(int32_t pid) SEN_HILOGE("Parcel write descriptor failed"); return WRITE_PARCEL_ERR; } - if (!data.WriteInt32(pid)) { - SEN_HILOGE("Parcel write pid failed"); - return WRITE_PARCEL_ERR; - } + WRITEINT32(data, pid, WRITE_PARCEL_ERR); sptr remote = Remote(); CHKPR(remote, ERROR); MessageParcel reply; @@ -217,10 +196,7 @@ ErrCode SensorServiceProxy::ResumeSensors(int32_t pid) SEN_HILOGE("Parcel write descriptor failed"); return WRITE_PARCEL_ERR; } - if (!data.WriteInt32(pid)) { - SEN_HILOGE("Parcel write pid failed"); - return WRITE_PARCEL_ERR; - } + WRITEINT32(data, pid, WRITE_PARCEL_ERR); sptr remote = Remote(); CHKPR(remote, ERROR); MessageParcel reply; @@ -241,10 +217,7 @@ ErrCode SensorServiceProxy::GetActiveInfoList(int32_t pid, std::vector remote = Remote(); CHKPR(remote, ERROR); MessageParcel reply; @@ -257,10 +230,7 @@ ErrCode SensorServiceProxy::GetActiveInfoList(int32_t pid, std::vector(ret); } size_t activeInfoCount; - if (!reply.ReadUint32(activeInfoCount)) { - SEN_HILOGE("Parcel read activeInfoCount failed"); - return READ_PARCEL_ERR; - } + READUINT32(reply, activeInfoCount, READ_PARCEL_ERR); ActiveInfo activeInfo; for (size_t i = 0; i < activeInfoCount; ++i) { auto tmpActiveInfo = activeInfo.Unmarshalling(reply); @@ -281,10 +251,7 @@ ErrCode SensorServiceProxy::CreateSocketChannel(sptr sensorClient SEN_HILOGE("Parcel write descriptor failed"); return WRITE_PARCEL_ERR; } - if (!data.WriteRemoteObject(sensorClient)) { - SEN_HILOGE("Parcel write sensorClient failed"); - return WRITE_PARCEL_ERR; - } + WRITEREMOTEOBJECT(data, sensorClient, WRITE_PARCEL_ERR); MessageParcel reply; MessageOption option; sptr remote = Remote(); @@ -312,10 +279,7 @@ ErrCode SensorServiceProxy::DestroySocketChannel(sptr sensorClien SEN_HILOGE("Parcel write descriptor failed"); return WRITE_PARCEL_ERR; } - if (!data.WriteRemoteObject(sensorClient)) { - SEN_HILOGE("Parcel write sensorClient failed"); - return WRITE_PARCEL_ERR; - } + WRITEREMOTEOBJECT(data, sensorClient, WRITE_PARCEL_ERR); sptr remote = Remote(); CHKPR(remote, ERROR); MessageParcel reply; diff --git a/services/sensor/src/sensor_service_stub.cpp b/services/sensor/src/sensor_service_stub.cpp index b3b00c2a..cd3b9380 100755 --- a/services/sensor/src/sensor_service_stub.cpp +++ b/services/sensor/src/sensor_service_stub.cpp @@ -25,6 +25,7 @@ #include "message_parcel.h" #include "permission_util.h" #include "sensor_client_proxy.h" +#include "sensor_parcel.h" #include "sensors_errors.h" namespace OHOS { @@ -82,24 +83,19 @@ ErrCode SensorServiceStub::SensorEnableInner(MessageParcel &data, MessageParcel { (void)reply; int32_t sensorId; - if (!data.ReadInt32(sensorId)) { - SEN_HILOGE("Parcel read failed"); - return ERROR; - } + READINT32(data, sensorId, READ_PARCEL_ERR); PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); int32_t ret = permissionUtil.CheckSensorPermission(GetCallingTokenID(), sensorId); if (ret != PERMISSION_GRANTED) { HiSysEventWrite(HiSysEvent::Domain::SENSOR, "VERIFY_ACCESS_TOKEN_FAIL", HiSysEvent::EventType::SECURITY, "PKG_NAME", "SensorEnableInner", "ERROR_CODE", ret); - SEN_HILOGE("sensorId:%{public}u grant failed,result:%{public}d", sensorId, ret); + SEN_HILOGE("sensorId:%{public}d grant failed, result:%{public}d", sensorId, ret); return PERMISSION_DENIED; } int64_t samplingPeriodNs; int64_t maxReportDelayNs; - if ((!data.ReadInt64(samplingPeriodNs)) || (!data.ReadInt64(maxReportDelayNs))) { - SEN_HILOGE("Parcel read failed"); - return ERROR; - } + READINT64(data, samplingPeriodNs, READ_PARCEL_ERR); + READINT64(data, maxReportDelayNs, READ_PARCEL_ERR); return EnableSensor(sensorId, samplingPeriodNs, maxReportDelayNs); } @@ -107,16 +103,13 @@ ErrCode SensorServiceStub::SensorDisableInner(MessageParcel &data, MessageParcel { (void)reply; int32_t sensorId; - if (!data.ReadInt32(sensorId)) { - SEN_HILOGE("Parcel read failed"); - return ERROR; - } + READINT32(data, sensorId, READ_PARCEL_ERR); PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); int32_t ret = permissionUtil.CheckSensorPermission(GetCallingTokenID(), sensorId); if (ret != PERMISSION_GRANTED) { HiSysEventWrite(HiSysEvent::Domain::SENSOR, "VERIFY_ACCESS_TOKEN_FAIL", HiSysEvent::EventType::SECURITY, "PKG_NAME", "SensorDisableInner", "ERROR_CODE", ret); - SEN_HILOGE("sensorId:%{public}u grant failed,result:%{public}d", sensorId, ret); + SEN_HILOGE("sensorId:%{public}d grant failed, result:%{public}d", sensorId, ret); return PERMISSION_DENIED; } return DisableSensor(sensorId); @@ -125,13 +118,12 @@ ErrCode SensorServiceStub::SensorDisableInner(MessageParcel &data, MessageParcel ErrCode SensorServiceStub::GetAllSensorsInner(MessageParcel &data, MessageParcel &reply) { (void)data; - std::vector sensors(GetSensorList()); - int32_t sensorCount = int32_t { sensors.size() }; - reply.WriteInt32(sensorCount); - for (int32_t i = 0; i < sensorCount; i++) { - bool flag = sensors[i].Marshalling(reply); - if (!flag) { - SEN_HILOGE("sensor %{public}d failed", i); + std::vector sensors = GetSensorList(); + int32_t sensorCount = sensors.size(); + WRITEINT32(reply, sensorCount, WRITE_PARCEL_ERR); + for (int32_t i = 0; i < sensorCount; ++i) { + if (!sensors[i].Marshalling(reply)) { + SEN_HILOGE("Sensor %{public}d marshalling failed", i); return GET_SENSOR_LIST_ERR; } } @@ -169,10 +161,7 @@ ErrCode SensorServiceStub::SuspendSensorsInner(MessageParcel &data, MessageParce } (void)reply; int32_t pid; - if (!data.ReadInt32(pid)) { - SEN_HILOGE("Parcel read pid failed"); - return READ_PARCEL_ERR; - } + READINT32(data, pid, READ_PARCEL_ERR); return SuspendSensors(pid); } @@ -185,10 +174,7 @@ ErrCode SensorServiceStub::ResumeSensorsInner(MessageParcel &data, MessageParcel } (void)reply; int32_t pid; - if (!data.ReadInt32(pid)) { - SEN_HILOGE("Parcel read pid failed"); - return READ_PARCEL_ERR; - } + READINT32(data, pid, READ_PARCEL_ERR); return ResumeSensors(pid); } @@ -200,10 +186,7 @@ ErrCode SensorServiceStub::GetActiveInfoListInner(MessageParcel &data, MessagePa return PERMISSION_DENIED; } int32_t pid; - if (!data.ReadInt32(pid)) { - SEN_HILOGE("Parcel read pid failed"); - return READ_PARCEL_ERR; - } + READINT32(data, pid, READ_PARCEL_ERR); std::vector activeInfoList; int32_t ret = GetActiveInfoList(pid, activeInfoList); if (ret != ERR_OK) { @@ -211,11 +194,8 @@ ErrCode SensorServiceStub::GetActiveInfoListInner(MessageParcel &data, MessagePa return ret; } size_t activeInfoCount = activeInfoList.size(); - if (!reply.WriteUint32(activeInfoCount)) { - SEN_HILOGE("Parcel write activeInfoCount failed"); - return WRITE_PARCEL_ERR; - } - for (size_t i = 0; i < activeInfoCount; i++) { + WRITEUINT32(reply, activeInfoCount, WRITE_PARCEL_ERR); + for (size_t i = 0; i < activeInfoCount; ++i) { if (!activeInfoList[i].Marshalling(reply)) { SEN_HILOGE("ActiveInfo %{public}zu marshalling failed", i); return WRITE_PARCEL_ERR; diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index ec9a7efa..a679ddf9 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -67,20 +67,14 @@ int32_t StreamServer::GetClientFd(int32_t pid) { std::lock_guard sessionLock(sessionMutex_); auto it = idxPidMap_.find(pid); - if (it == idxPidMap_.end()) { - return INVALID_FD; - } - return it->second; + return it == idxPidMap_.end() ? INVALID_FD : it->second; } int32_t StreamServer::GetClientPid(int32_t fd) { std::lock_guard sessionLock(sessionMutex_); auto it = sessionsMap_.find(fd); - if (it == sessionsMap_.end()) { - return INVALID_PID; - } - return it->second->GetPid(); + return it == sessionsMap_.end() ? INVALID_PID : it->second->GetPid(); } SessionPtr StreamServer::GetSession(int32_t fd) @@ -197,7 +191,7 @@ void StreamServer::DelSession(int32_t pid) if (fd >= 0) { auto rf = close(fd); if (rf != 0) { - SEN_HILOGE("Socket fd close failed, rf:%{public}d", rf); + SEN_HILOGE("Socket fd close failed, rf:%{public}d, errno:%{public}d", rf, errno); } } } diff --git a/utils/common/include/sensor_parcel.h b/utils/common/include/sensor_parcel.h new file mode 100644 index 00000000..f2aaa065 --- /dev/null +++ b/utils/common/include/sensor_parcel.h @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef SENSOR_PARCEL_H +#define SENSOR_PARCEL_H + +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { + +#define WRITEBOOL(parcel, data, ...) \ + do { \ + if (!(parcel).WriteBool(data)) { \ + SEN_HILOGE("Parcel writeBool "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define WRITEINT32(parcel, data, ...) \ + do { \ + if (!(parcel).WriteInt32(data)) { \ + SEN_HILOGE("Parcel writeInt32 "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define WRITEINT64(parcel, data, ...) \ + do { \ + if (!(parcel).WriteInt64(data)) { \ + SEN_HILOGE("Parcel writeInt64 "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define WRITEUINT32(parcel, data, ...) \ + do { \ + if (!(parcel).WriteUint32(data)) { \ + SEN_HILOGE("Parcel writeUint32 "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define WRITEDOUBLE(parcel, data, ...) \ + do { \ + if (!(parcel).WriteDouble(data)) { \ + SEN_HILOGE("Parcel writeDouble "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define WRITESTRING(parcel, data, ...) \ + do { \ + if (!(parcel).WriteString(data)) { \ + SEN_HILOGE("Parcel writeString "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define WRITESTRING16(parcel, data, ...) \ + do { \ + if (!(parcel).WriteString16(data)) { \ + SEN_HILOGE("Parcel writeString16 "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define WRITEREMOTEOBJECT(parcel, data, ...) \ + do { \ + if (!(parcel).WriteRemoteObject(data)) { \ + SEN_HILOGE("Parcel writeRemoteObject "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define WRITEUINT8VECTOR(parcel, data, ...) \ + do { \ + if (!(parcel).WriteUInt8Vector(data)) { \ + SEN_HILOGE("Parcel writeUInt8Vector "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define READBOOL(parcel, data, ...) \ + do { \ + if (!(parcel).ReadBool(data)) { \ + SEN_HILOGE("Parcel readBool "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define READINT32(parcel, data, ...) \ + do { \ + if (!(parcel).ReadInt32(data)) { \ + SEN_HILOGE("Parcel readInt32 "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define READINT64(parcel, data, ...) \ + do { \ + if (!(parcel).ReadInt64(data)) { \ + SEN_HILOGE("Parcel readInt64 "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define READUINT32(parcel, data, ...) \ + do { \ + if (!(parcel).ReadUint32(data)) { \ + SEN_HILOGE("Parcel readUint32 "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define READDOUBLE(parcel, data, ...) \ + do { \ + if (!(parcel).ReadDouble(data)) { \ + SEN_HILOGE("Parcel readDouble "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define READSTRING(parcel, data, ...) \ + do { \ + if (!(parcel).ReadString(data)) { \ + SEN_HILOGE("Parcel readString "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define READUINT8VECTOR(parcel, data, ...) \ + do { \ + if (!(parcel).ReadUInt8Vector(&data)) { \ + SEN_HILOGE("Parcel readUInt8Vector "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) + +#define READSTRING16(parcel, data, ...) \ + do { \ + if (!(parcel).ReadString16(data)) { \ + SEN_HILOGE("Parcel readString16 "#data" failed"); \ + return __VA_ARGS__; \ + } \ + } while (0) +} // namespace Sensors +} // namespace OHOS +#endif // SENSOR_PARCEL_H \ No newline at end of file diff --git a/utils/common/src/sensor.cpp b/utils/common/src/sensor.cpp index 485b4671..32e3c4c7 100644 --- a/utils/common/src/sensor.cpp +++ b/utils/common/src/sensor.cpp @@ -172,11 +172,11 @@ void Sensor::SetMaxSamplePeriodNs(int64_t maxSamplePeriodNs) bool Sensor::Marshalling(Parcel &parcel) const { - if (!parcel.WriteUint32(sensorId_)) { + if (!parcel.WriteInt32(sensorId_)) { SEN_HILOGE("failed, write sensorId failed"); return false; } - if (!parcel.WriteUint32(sensorTypeId_)) { + if (!parcel.WriteInt32(sensorTypeId_)) { SEN_HILOGE("failed, write sensorTypeId failed"); return false; } -- Gitee From 595b8490e11dc056f26f088e2ae2f07dcf43171d Mon Sep 17 00:00:00 2001 From: hui1975 Date: Fri, 21 Apr 2023 08:14:56 +0000 Subject: [PATCH 41/53] update Signed-off-by: hui1975 Change-Id: Ib9c6bbd6d00e1f61b7951d190e10634009315520 --- frameworks/native/sensor/src/sensor_service_proxy.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 3f8ac241..6456ce91 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -20,6 +20,7 @@ #include "hisysevent.h" #include "message_parcel.h" #include "sensor_client_proxy.h" +#include "sensor_parcel.h" #include "sensors_errors.h" namespace OHOS { -- Gitee From 251649c581fdea5f458568d905de07972a9a661a Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 24 Apr 2023 03:10:37 +0000 Subject: [PATCH 42/53] update Signed-off-by: hui1975 Change-Id: I1ad68d227beb6340e131f4468e428f115ae02219 --- services/sensor/src/stream_server.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index a679ddf9..ffecd5a3 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -111,25 +111,25 @@ int32_t StreamServer::AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenT serverFd = sockFds[0]; clientFd = sockFds[1]; if (serverFd < 0 || clientFd < 0) { - SEN_HILOGE("Call fcntl failed, errno:%{public}d", errno); + SEN_HILOGE("Call socketpair failed, errno:%{public}d", errno); return ERROR; } static constexpr size_t bufferSize = 32 * 1024; SessionPtr sess = nullptr; if (setsockopt(serverFd, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt serverFd failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt serverFd buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } if (setsockopt(serverFd, SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt serverFd failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt serverFd buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } if (setsockopt(clientFd, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt clientFd buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } if (setsockopt(clientFd, SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt clientFd failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt clientFd buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } sess = std::make_shared("", serverFd, uid, pid); -- Gitee From 09b873204fe14f56d880d9e28e78f1e30811b15e Mon Sep 17 00:00:00 2001 From: hui1975 Date: Thu, 27 Apr 2023 01:44:11 +0000 Subject: [PATCH 43/53] update Signed-off-by: hui1975 Change-Id: I74f9dfe8cb8619443b7f2d4876c96856d45cee0b --- .../sensor/src/sensor_service_proxy.cpp | 8 +-- interfaces/native/test/fuzztest/BUILD.gn | 9 +-- .../getsensoractiveinfos_fuzzer/BUILD.gn | 51 --------------- .../getsensoractiveinfos_fuzzer/corpus/init | 14 ----- .../getsensoractiveinfos_fuzzer.cpp | 63 ------------------- .../getsensoractiveinfos_fuzzer.h | 22 ------- .../getsensoractiveinfos_fuzzer/project.xml | 25 -------- .../BUILD.gn | 51 --------------- .../corpus/init | 14 ----- .../project.xml | 25 -------- .../registersensoractiveInfocb_fuzzer.cpp | 61 ------------------ .../registersensoractiveInfocb_fuzzer.h | 22 ------- .../fuzztest/resumesensors_fuzzer/BUILD.gn | 51 --------------- .../fuzztest/resumesensors_fuzzer/corpus/init | 14 ----- .../fuzztest/resumesensors_fuzzer/project.xml | 25 -------- .../resumesensors_fuzzer.cpp | 60 ------------------ .../resumesensors_fuzzer.h | 22 ------- .../fuzztest/suspendsensors_fuzzer/BUILD.gn | 51 --------------- .../suspendsensors_fuzzer/corpus/init | 14 ----- .../suspendsensors_fuzzer/project.xml | 25 -------- .../suspendsensors_fuzzer.cpp | 60 ------------------ .../suspendsensors_fuzzer.h | 22 ------- .../BUILD.gn | 51 --------------- .../corpus/init | 14 ----- .../project.xml | 25 -------- .../unregistersensoractiveInfocb_fuzzer.cpp | 61 ------------------ .../unregistersensoractiveInfocb_fuzzer.h | 22 ------- services/sensor/src/sensor_service_stub.cpp | 8 +-- 28 files changed, 9 insertions(+), 881 deletions(-) delete mode 100644 interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/BUILD.gn delete mode 100644 interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/corpus/init delete mode 100644 interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.cpp delete mode 100644 interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.h delete mode 100644 interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/project.xml delete mode 100644 interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/BUILD.gn delete mode 100644 interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/corpus/init delete mode 100644 interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/project.xml delete mode 100644 interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.cpp delete mode 100644 interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.h delete mode 100644 interfaces/native/test/fuzztest/resumesensors_fuzzer/BUILD.gn delete mode 100644 interfaces/native/test/fuzztest/resumesensors_fuzzer/corpus/init delete mode 100644 interfaces/native/test/fuzztest/resumesensors_fuzzer/project.xml delete mode 100644 interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.cpp delete mode 100644 interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.h delete mode 100644 interfaces/native/test/fuzztest/suspendsensors_fuzzer/BUILD.gn delete mode 100644 interfaces/native/test/fuzztest/suspendsensors_fuzzer/corpus/init delete mode 100644 interfaces/native/test/fuzztest/suspendsensors_fuzzer/project.xml delete mode 100644 interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.cpp delete mode 100644 interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.h delete mode 100644 interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/BUILD.gn delete mode 100644 interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/corpus/init delete mode 100644 interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/project.xml delete mode 100644 interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.cpp delete mode 100644 interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.h diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 6456ce91..3dae4704 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -230,13 +230,13 @@ ErrCode SensorServiceProxy::GetActiveInfoList(int32_t pid, std::vector(ret); } - size_t activeInfoCount; - READUINT32(reply, activeInfoCount, READ_PARCEL_ERR); + int32_t activeInfoCount; + READINT32(reply, activeInfoCount, READ_PARCEL_ERR); ActiveInfo activeInfo; - for (size_t i = 0; i < activeInfoCount; ++i) { + for (int32_t i = 0; i < activeInfoCount; ++i) { auto tmpActiveInfo = activeInfo.Unmarshalling(reply); if (tmpActiveInfo == nullptr) { - SEN_HILOGE("Current activeInfo is nullptr, i:%{public}zu", i); + SEN_HILOGE("Current activeInfo is nullptr, i:%{public}d", i); continue; } activeInfoList.push_back(*tmpActiveInfo); diff --git a/interfaces/native/test/fuzztest/BUILD.gn b/interfaces/native/test/fuzztest/BUILD.gn index f5165696..bd9265b3 100644 --- a/interfaces/native/test/fuzztest/BUILD.gn +++ b/interfaces/native/test/fuzztest/BUILD.gn @@ -17,12 +17,5 @@ import("//build/test.gni") group("fuzztest") { testonly = true - deps = [ - "sensoragent_fuzzer:fuzztest", - "suspendsensors_fuzzer:fuzztest", - "resumesensors_fuzzer:fuzztest", - "getsensoractiveinfos_fuzzer:fuzztest", - "registersensoractiveInfocb_fuzzer:fuzztest", - "unregistersensoractiveInfocb_fuzzer:fuzztest", - ] + deps = [ "sensoragent_fuzzer:fuzztest" ] } diff --git a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/BUILD.gn b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/BUILD.gn deleted file mode 100644 index 71efd222..00000000 --- a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/BUILD.gn +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/config/features.gni") -import("//build/ohos.gni") -import("//build/test.gni") -module_output_path = "sensors/sensor" - -ohos_fuzztest("GetSensorActiveInfosFuzzTest") { - module_out_path = module_output_path - - fuzz_config_file = - "//base/sensors/sensor/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer" - - include_dirs = [ - "//base/sensors/sensor/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer", - "//base/sensors/sensor/interfaces/native/include", - ] - - cflags = [ - "-g", - "-O0", - "-Wno-unused-variable", - "-fno-omit-frame-pointer", - ] - - sources = [ "getsensoractiveinfos_fuzzer.cpp" ] - - deps = [ "//base/sensors/sensor/interfaces/native:sensor_interface_native" ] - - external_deps = [ "c_utils:utils" ] -} - -group("fuzztest") { - testonly = true - deps = [] - deps += [ - # deps file - ":GetSensorActiveInfosFuzzTest", - ] -} diff --git a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/corpus/init b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/corpus/init deleted file mode 100644 index f8128231..00000000 --- a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/corpus/init +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FUZZ \ No newline at end of file diff --git a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.cpp b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.cpp deleted file mode 100644 index a7ee7dd3..00000000 --- a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "getsensoractiveinfos_fuzzer.h" - -#include "securec.h" - -#include "sensor_agent.h" -#include "sensor_agent_type.h" - -namespace OHOS { -namespace Sensors { -namespace { -constexpr size_t DATA_MIN_SIZE = 4; -} // namespace - -template -size_t GetObject(const uint8_t *data, size_t size, T &object) -{ - size_t objectSize = sizeof(object); - if (objectSize > size) { - return 0; - } - errno_t ret = memcpy_s(&object, objectSize, data, objectSize); - if (ret != EOK) { - return 0; - } - return objectSize; -} - -void GetSensorActiveInfosFuzzTest(const uint8_t* data, size_t size) -{ - if (data == nullptr || size < DATA_MIN_SIZE) { - return; - } - size_t startPos = 0; - int32_t pid {-1}; - GetObject(data + startPos, size - startPos, pid); - SensorActiveInfo *sensorActiveInfos {nullptr}; - int32_t count { 0 }; - GetSensorActiveInfos(pid, &sensorActiveInfos, &count); -} -} // Sensors -} // OHOS - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) -{ - OHOS::Sensors::GetSensorActiveInfosFuzzTest(data, size); - return 0; -} - diff --git a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.h b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.h deleted file mode 100644 index 99e91497..00000000 --- a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/getsensoractiveinfos_fuzzer.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SENSOR_DISABLE_FUZZER_H -#define SENSOR_DISABLE_FUZZER_H - -#define FUZZ_PROJECT_NAME "getsensoractiveinfos_fuzzer" - -#endif - diff --git a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/project.xml b/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/project.xml deleted file mode 100644 index 20dc766d..00000000 --- a/interfaces/native/test/fuzztest/getsensoractiveinfos_fuzzer/project.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - 1000 - - 120 - - 2048 - - diff --git a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/BUILD.gn b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/BUILD.gn deleted file mode 100644 index 862c46b8..00000000 --- a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/BUILD.gn +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/config/features.gni") -import("//build/ohos.gni") -import("//build/test.gni") -module_output_path = "sensors/sensor" - -ohos_fuzztest("RegisterSensorActiveInfoCBFuzzTest") { - module_out_path = module_output_path - - fuzz_config_file = - "//base/sensors/sensor/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer" - - include_dirs = [ - "//base/sensors/sensor/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer", - "//base/sensors/sensor/interfaces/native/include", - ] - - cflags = [ - "-g", - "-O0", - "-Wno-unused-variable", - "-fno-omit-frame-pointer", - ] - - sources = [ "registersensoractiveInfocb_fuzzer.cpp" ] - - deps = [ "//base/sensors/sensor/interfaces/native:sensor_interface_native" ] - - external_deps = [ "c_utils:utils" ] -} - -group("fuzztest") { - testonly = true - deps = [] - deps += [ - # deps file - ":RegisterSensorActiveInfoCBFuzzTest", - ] -} diff --git a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/corpus/init b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/corpus/init deleted file mode 100644 index f8128231..00000000 --- a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/corpus/init +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FUZZ \ No newline at end of file diff --git a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/project.xml b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/project.xml deleted file mode 100644 index 20dc766d..00000000 --- a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/project.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - 1000 - - 120 - - 2048 - - diff --git a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.cpp b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.cpp deleted file mode 100644 index dcab8db3..00000000 --- a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "registersensoractiveInfocb_fuzzer.h" - -#include "securec.h" - -#include "sensor_agent.h" -#include "sensor_agent_type.h" - -namespace OHOS { -namespace Sensors { -namespace { -constexpr size_t DATA_MIN_SIZE = 4; -} // namespace - -template -size_t GetObject(const uint8_t *data, size_t size, T &object) -{ - size_t objectSize = sizeof(object); - if (objectSize > size) { - return 0; - } - errno_t ret = memcpy_s(&object, objectSize, data, objectSize); - if (ret != EOK) { - return 0; - } - return objectSize; -} - -void RegisterSensorActiveInfoCBFuzzTest(const uint8_t* data, size_t size) -{ - if (data == nullptr || size < DATA_MIN_SIZE) { - return; - } - size_t startPos = 0; - SensorActiveInfoCB callback = nullptr; - GetObject(data + startPos, size - startPos, callback); - RegisterSensorActiveInfoCB(callback); -} -} // Sensors -} // OHOS - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) -{ - OHOS::Sensors::RegisterSensorActiveInfoCBFuzzTest(data, size); - return 0; -} - diff --git a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.h b/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.h deleted file mode 100644 index e5481f6f..00000000 --- a/interfaces/native/test/fuzztest/registersensoractiveInfocb_fuzzer/registersensoractiveInfocb_fuzzer.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SENSOR_DISABLE_FUZZER_H -#define SENSOR_DISABLE_FUZZER_H - -#define FUZZ_PROJECT_NAME "registersensoractiveInfocb_fuzzer" - -#endif - diff --git a/interfaces/native/test/fuzztest/resumesensors_fuzzer/BUILD.gn b/interfaces/native/test/fuzztest/resumesensors_fuzzer/BUILD.gn deleted file mode 100644 index 65b0f4a8..00000000 --- a/interfaces/native/test/fuzztest/resumesensors_fuzzer/BUILD.gn +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/config/features.gni") -import("//build/ohos.gni") -import("//build/test.gni") -module_output_path = "sensors/sensor" - -ohos_fuzztest("ResumeSensorsFuzzTest") { - module_out_path = module_output_path - - fuzz_config_file = - "//base/sensors/sensor/interfaces/native/test/fuzztest/resumesensors_fuzzer" - - include_dirs = [ - "//base/sensors/sensor/interfaces/native/test/fuzztest/resumesensors_fuzzer", - "//base/sensors/sensor/interfaces/native/include", - ] - - cflags = [ - "-g", - "-O0", - "-Wno-unused-variable", - "-fno-omit-frame-pointer", - ] - - sources = [ "resumesensors_fuzzer.cpp" ] - - deps = [ "//base/sensors/sensor/interfaces/native:sensor_interface_native" ] - - external_deps = [ "c_utils:utils" ] -} - -group("fuzztest") { - testonly = true - deps = [] - deps += [ - # deps file - ":ResumeSensorsFuzzTest", - ] -} diff --git a/interfaces/native/test/fuzztest/resumesensors_fuzzer/corpus/init b/interfaces/native/test/fuzztest/resumesensors_fuzzer/corpus/init deleted file mode 100644 index f8128231..00000000 --- a/interfaces/native/test/fuzztest/resumesensors_fuzzer/corpus/init +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FUZZ \ No newline at end of file diff --git a/interfaces/native/test/fuzztest/resumesensors_fuzzer/project.xml b/interfaces/native/test/fuzztest/resumesensors_fuzzer/project.xml deleted file mode 100644 index 20dc766d..00000000 --- a/interfaces/native/test/fuzztest/resumesensors_fuzzer/project.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - 1000 - - 120 - - 2048 - - diff --git a/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.cpp b/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.cpp deleted file mode 100644 index 8c024ba4..00000000 --- a/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "resumesensors_fuzzer.h" - -#include "securec.h" - -#include "sensor_agent.h" - -namespace OHOS { -namespace Sensors { -namespace { -constexpr size_t DATA_MIN_SIZE = 4; -} // namespace - -template -size_t GetObject(const uint8_t *data, size_t size, T &object) -{ - size_t objectSize = sizeof(object); - if (objectSize > size) { - return 0; - } - errno_t ret = memcpy_s(&object, objectSize, data, objectSize); - if (ret != EOK) { - return 0; - } - return objectSize; -} - -void ResumeSensorsFuzzTest(const uint8_t* data, size_t size) -{ - if (data == nullptr || size < DATA_MIN_SIZE) { - return; - } - size_t startPos = 0; - int32_t pid {-1}; - GetObject(data + startPos, size - startPos, pid); - ResumeSensors(pid); -} -} // Sensors -} // OHOS - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) -{ - OHOS::Sensors::ResumeSensorsFuzzTest(data, size); - return 0; -} - diff --git a/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.h b/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.h deleted file mode 100644 index 97516a76..00000000 --- a/interfaces/native/test/fuzztest/resumesensors_fuzzer/resumesensors_fuzzer.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SENSOR_DISABLE_FUZZER_H -#define SENSOR_DISABLE_FUZZER_H - -#define FUZZ_PROJECT_NAME "resumesensors_fuzzer" - -#endif - diff --git a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/BUILD.gn b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/BUILD.gn deleted file mode 100644 index d20b18e4..00000000 --- a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/BUILD.gn +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/config/features.gni") -import("//build/ohos.gni") -import("//build/test.gni") -module_output_path = "sensors/sensor" - -ohos_fuzztest("SuspendSensorsFuzzTest") { - module_out_path = module_output_path - - fuzz_config_file = - "//base/sensors/sensor/interfaces/native/test/fuzztest/suspendsensors_fuzzer" - - include_dirs = [ - "//base/sensors/sensor/interfaces/native/test/fuzztest/suspendsensors_fuzzer", - "//base/sensors/sensor/interfaces/native/include", - ] - - cflags = [ - "-g", - "-O0", - "-Wno-unused-variable", - "-fno-omit-frame-pointer", - ] - - sources = [ "suspendsensors_fuzzer.cpp" ] - - deps = [ "//base/sensors/sensor/interfaces/native:sensor_interface_native" ] - - external_deps = [ "c_utils:utils" ] -} - -group("fuzztest") { - testonly = true - deps = [] - deps += [ - # deps file - ":SuspendSensorsFuzzTest", - ] -} diff --git a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/corpus/init b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/corpus/init deleted file mode 100644 index f8128231..00000000 --- a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/corpus/init +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FUZZ \ No newline at end of file diff --git a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/project.xml b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/project.xml deleted file mode 100644 index 20dc766d..00000000 --- a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/project.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - 1000 - - 120 - - 2048 - - diff --git a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.cpp b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.cpp deleted file mode 100644 index 60c60a53..00000000 --- a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "suspendsensors_fuzzer.h" - -#include "securec.h" - -#include "sensor_agent.h" - -namespace OHOS { -namespace Sensors { -namespace { -constexpr size_t DATA_MIN_SIZE = 4; -} // namespace - -template -size_t GetObject(const uint8_t *data, size_t size, T &object) -{ - size_t objectSize = sizeof(object); - if (objectSize > size) { - return 0; - } - errno_t ret = memcpy_s(&object, objectSize, data, objectSize); - if (ret != EOK) { - return 0; - } - return objectSize; -} - -void SuspendSensorsFuzzTest(const uint8_t* data, size_t size) -{ - if (data == nullptr || size < DATA_MIN_SIZE) { - return; - } - size_t startPos = 0; - int32_t pid {-1}; - GetObject(data + startPos, size - startPos, pid); - SuspendSensors(pid); -} -} // Sensors -} // OHOS - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) -{ - OHOS::Sensors::SuspendSensorsFuzzTest(data, size); - return 0; -} - diff --git a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.h b/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.h deleted file mode 100644 index 11db9b6b..00000000 --- a/interfaces/native/test/fuzztest/suspendsensors_fuzzer/suspendsensors_fuzzer.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SENSOR_DISABLE_FUZZER_H -#define SENSOR_DISABLE_FUZZER_H - -#define FUZZ_PROJECT_NAME "suspendsensors_fuzzer" - -#endif - diff --git a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/BUILD.gn b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/BUILD.gn deleted file mode 100644 index 23398fcf..00000000 --- a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/BUILD.gn +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/config/features.gni") -import("//build/ohos.gni") -import("//build/test.gni") -module_output_path = "sensors/sensor" - -ohos_fuzztest("UnregisterSensorActiveInfoCBFuzzTest") { - module_out_path = module_output_path - - fuzz_config_file = - "//base/sensors/sensor/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer" - - include_dirs = [ - "//base/sensors/sensor/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer", - "//base/sensors/sensor/interfaces/native/include", - ] - - cflags = [ - "-g", - "-O0", - "-Wno-unused-variable", - "-fno-omit-frame-pointer", - ] - - sources = [ "unregistersensoractiveInfocb_fuzzer.cpp" ] - - deps = [ "//base/sensors/sensor/interfaces/native:sensor_interface_native" ] - - external_deps = [ "c_utils:utils" ] -} - -group("fuzztest") { - testonly = true - deps = [] - deps += [ - # deps file - ":UnregisterSensorActiveInfoCBFuzzTest", - ] -} diff --git a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/corpus/init b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/corpus/init deleted file mode 100644 index f8128231..00000000 --- a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/corpus/init +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FUZZ \ No newline at end of file diff --git a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/project.xml b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/project.xml deleted file mode 100644 index 20dc766d..00000000 --- a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/project.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - 1000 - - 120 - - 2048 - - diff --git a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.cpp b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.cpp deleted file mode 100644 index c2d03be0..00000000 --- a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "unregistersensoractiveInfocb_fuzzer.h" - -#include "securec.h" - -#include "sensor_agent.h" -#include "sensor_agent_type.h" - -namespace OHOS { -namespace Sensors { -namespace { -constexpr size_t DATA_MIN_SIZE = 4; -} // namespace - -template -size_t GetObject(const uint8_t *data, size_t size, T &object) -{ - size_t objectSize = sizeof(object); - if (objectSize > size) { - return 0; - } - errno_t ret = memcpy_s(&object, objectSize, data, objectSize); - if (ret != EOK) { - return 0; - } - return objectSize; -} - -void UnregisterSensorActiveInfoCBFuzzTest(const uint8_t* data, size_t size) -{ - if (data == nullptr || size < DATA_MIN_SIZE) { - return; - } - size_t startPos = 0; - SensorActiveInfoCB callback = nullptr; - GetObject(data + startPos, size - startPos, callback); - UnregisterSensorActiveInfoCB(callback); -} -} // Sensors -} // OHOS - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) -{ - OHOS::Sensors::UnregisterSensorActiveInfoCBFuzzTest(data, size); - return 0; -} - diff --git a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.h b/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.h deleted file mode 100644 index 380152c8..00000000 --- a/interfaces/native/test/fuzztest/unregistersensoractiveInfocb_fuzzer/unregistersensoractiveInfocb_fuzzer.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SENSOR_DISABLE_FUZZER_H -#define SENSOR_DISABLE_FUZZER_H - -#define FUZZ_PROJECT_NAME "unregistersensoractiveinfocb_fuzzer" - -#endif - diff --git a/services/sensor/src/sensor_service_stub.cpp b/services/sensor/src/sensor_service_stub.cpp index cd3b9380..f1b97994 100755 --- a/services/sensor/src/sensor_service_stub.cpp +++ b/services/sensor/src/sensor_service_stub.cpp @@ -193,11 +193,11 @@ ErrCode SensorServiceStub::GetActiveInfoListInner(MessageParcel &data, MessagePa SEN_HILOGE("Get activeInfo list failed"); return ret; } - size_t activeInfoCount = activeInfoList.size(); - WRITEUINT32(reply, activeInfoCount, WRITE_PARCEL_ERR); - for (size_t i = 0; i < activeInfoCount; ++i) { + int32_t activeInfoCount = activeInfoList.size(); + WRITEINT32(reply, activeInfoCount, WRITE_PARCEL_ERR); + for (int32_t i = 0; i < activeInfoCount; ++i) { if (!activeInfoList[i].Marshalling(reply)) { - SEN_HILOGE("ActiveInfo %{public}zu marshalling failed", i); + SEN_HILOGE("ActiveInfo %{public}d marshalling failed", i); return WRITE_PARCEL_ERR; } } -- Gitee From f1e38c2b3ffc36ba0a71c4e670e24097abe5783c Mon Sep 17 00:00:00 2001 From: hui1975 Date: Sat, 6 May 2023 03:22:28 +0000 Subject: [PATCH 44/53] update Signed-off-by: hui1975 Change-Id: I524058c8af2643bfddc20cd67623a7c6e012d57e --- frameworks/native/sensor/BUILD.gn | 2 +- services/sensor/src/sensor_power_policy.cpp | 48 ++++++++++++++++----- utils/common/include/sensors_errors.h | 2 + 3 files changed, 40 insertions(+), 12 deletions(-) diff --git a/frameworks/native/sensor/BUILD.gn b/frameworks/native/sensor/BUILD.gn index 52b0e4db..1ad00abc 100755 --- a/frameworks/native/sensor/BUILD.gn +++ b/frameworks/native/sensor/BUILD.gn @@ -35,7 +35,7 @@ ohos_shared_library("libsensor_native") { deps = [ "$SUBSYSTEM_DIR/utils/common:libsensor_utils", - "$SUBSYSTEM_DIR/sensor/utils/ipc:libsensor_ipc", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", ] external_deps = [ diff --git a/services/sensor/src/sensor_power_policy.cpp b/services/sensor/src/sensor_power_policy.cpp index b466037f..1fd09f52 100644 --- a/services/sensor/src/sensor_power_policy.cpp +++ b/services/sensor/src/sensor_power_policy.cpp @@ -41,26 +41,28 @@ ErrCode SensorPowerPolicy::SuspendSensors(int32_t pid) CALL_LOG_ENTER; std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); if (sensorIdList.empty()) { - SEN_HILOGW("SensorIdList is empty, pid not enable sensor or all sensor have bean suspend"); - return ERR_OK; + // 如果clientMap中没有当前pid的sensor信息,说明不需要休眠,直接返回失败 + SEN_HILOGE("Suspend sensor failed, sensorIdList is empty, pid:%{public}d", pid); + return SUSPEND_ERR; } std::lock_guard pidSensorInfoLock(pidSensorInfoMutex_); auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); if (pidSensorInfoIt != pidSensorInfoMap_.end()) { - SEN_HILOGI("Pid already call suspend, but some sensors suspend failed, suspend these sensors again"); + // policy中有数据,clientMap中也有数据 std::unordered_map sensorInfoMap = pidSensorInfoIt->second; if (!Suspend(pid, sensorIdList, sensorInfoMap)) { - SEN_HILOGE("Suspend last failed sensors, but some failed"); - return DISABLE_SENSOR_ERR; + SEN_HILOGE("Suspend part sensors, but some failed"); + return SUSPEND_ERR; } return ERR_OK; } + // 数据全部保存在clientMap中 std::unordered_map sensorInfoMap; auto isAllSuspend = Suspend(pid, sensorIdList, sensorInfoMap); pidSensorInfoMap_.insert(std::make_pair(pid, sensorInfoMap)); if (!isAllSuspend) { SEN_HILOGE("Suspend all sensors, but some failed"); - return DISABLE_SENSOR_ERR; + return SUSPEND_ERR; } return ERR_OK; } @@ -75,16 +77,29 @@ bool SensorPowerPolicy::Suspend(int32_t pid, std::vector &sensorIdList, SEN_HILOGD("Current sensor is pedometer detection or pedometer, can not suspend"); continue; } + // 检查当前sensorId是否在当前pid的白名单中,如果在,continue跳过 auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { SEN_HILOGD("Other client is using this sensor now, cannot suspend"); + sensorInfo.SetSensorState(false); // 休眠成功,将状态置为false,保存到policy中 sensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); continue; } - if (sensorHdiConnection_.DisableSensor(sensorId) != ERR_OK) { - SEN_HILOGE("Disable sensor failed, sensorId:%{public}d", sensorId); + + bool flag = false; + for (int32_t i = 0; i < 3; ++i) { + if (sensorHdiConnection_.DisableSensor(sensorId) == ERR_OK) { + flag = true; + break; + } + sleep(); + } + + if (flag == true) { + sensorInfo.SetSensorState(false); // 休眠成功,将状态置为false + } else { isAllSuspend = false; - continue; + sensorInfo.SetSensorState(true); // 休眠失败,将状态置为true } sensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); sensorManager_.AfterDisableSensor(sensorId); @@ -99,7 +114,7 @@ ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); if (pidSensorInfoIt == pidSensorInfoMap_.end()) { SEN_HILOGE("Pid not have suspend sensors"); - return ERROR; + return RESUME_ERR; } bool isAllResume = true; std::unordered_map sensorInfoMap = pidSensorInfoIt->second; @@ -107,6 +122,8 @@ ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) int32_t sensorId = sensorIt->first; int64_t samplingPeriodNs = sensorIt->second.GetSamplingPeriodNs(); int64_t maxReportDelayNs = sensorIt->second.GetMaxReportDelayNs(); + bool sensorState = sensorIt->second.GetSensorState(); + if (!Resume(pid, sensorId, samplingPeriodNs, maxReportDelayNs)) { SEN_HILOGE("Resume sensor failed. sensorId:%{public}d", sensorId); isAllResume = false; @@ -117,7 +134,7 @@ ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) } if (!isAllResume) { SEN_HILOGE("Some sensor resume failed"); - return ENABLE_SENSOR_ERR; + return RESUME_ERR; } pidSensorInfoMap_.erase(pidSensorInfoIt); return ERR_OK; @@ -133,14 +150,23 @@ bool SensorPowerPolicy::Resume(int32_t pid, int32_t sensorId, int64_t samplingPe return false; } if (clientInfo_.GetSensorState(sensorId)) { + //当前sensor已经被其他进程打开 SEN_HILOGD("Sensor is enable, sensorId:%{public}d", sensorId); auto ret = RestoreSensorInfo(pid, sensorId, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { SEN_HILOGE("Restore sensor info failed, ret:%{public}d", ret); + // 给clientMap中恢复信息失败 return false; } return true; } + // 当前sensor没有被其他进程打开 + // 如果 sensorstate == false, 说明suspend成功, 而且没被其他进程打开 + // 1. 给clientMap中恢复信息 + // 2. 三次重试打开传感器,打开失败时删除clientMap中恢复的信息 + // 如果 sensorstate == true, 说明suspend失败,而且没有被其他进程打开。 但此时sensor可能是打开状态也可能是关闭状态 + + auto ret = RestoreSensorInfo(pid, sensorId, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { SEN_HILOGE("Restore sensor info failed, ret:%{public}d", ret); diff --git a/utils/common/include/sensors_errors.h b/utils/common/include/sensors_errors.h index 43edceab..ed25743f 100644 --- a/utils/common/include/sensors_errors.h +++ b/utils/common/include/sensors_errors.h @@ -92,6 +92,8 @@ enum { SET_SENSOR_MODE_ERR = READ_PARCEL_ERR + 1, SET_SENSOR_OPTION_ERR = SET_SENSOR_MODE_ERR + 1, REGIST_CALLBACK_ERR = SET_SENSOR_OPTION_ERR + 1, + SUSPEND_ERR = REGIST_CALLBACK_ERR + 1; + RESUME_ERR = SUSPEND_ERR; }; // Error code for Sensor utils -- Gitee From ee3d27e364dd383dd4d59f1f18450ba3ed0ad608 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 8 May 2023 03:26:52 +0000 Subject: [PATCH 45/53] update Signed-off-by: hui1975 Change-Id: I6e79a3b4aef868322cb0d471e7c02cc8a51be327 --- services/sensor/include/sensor_service.h | 4 +-- services/sensor/include/stream_server.h | 2 +- services/sensor/src/sensor_service.cpp | 8 +++--- services/sensor/src/stream_server.cpp | 34 ++++++++++++------------ 4 files changed, 24 insertions(+), 24 deletions(-) diff --git a/services/sensor/include/sensor_service.h b/services/sensor/include/sensor_service.h index dff3c41a..2cc753c1 100644 --- a/services/sensor/include/sensor_service.h +++ b/services/sensor/include/sensor_service.h @@ -98,13 +98,13 @@ private: SensorHdiConnection &sensorHdiConnection_ = SensorHdiConnection::GetInstance(); ClientInfo &clientInfo_ = ClientInfo::GetInstance(); SensorManager &sensorManager_ = SensorManager::GetInstance(); - SensorPowerPolicy &sensorPowerPolicy_ = SensorPowerPolicy::GetInstance(); + using PowerPolicy = SensorPowerPolicy::GetInstance(); sptr sensorDataProcesser_ = nullptr; sptr reportDataCallback_ = nullptr; std::mutex uidLock_; // death recipient of sensor client sptr clientDeathObserver_ = nullptr; - std::shared_ptr permStateChangeCb_; + std::shared_ptr permStateChangeCb_ = nullptr; ErrCode SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); std::atomic_bool isReportActiveInfo_ = false; }; diff --git a/services/sensor/include/stream_server.h b/services/sensor/include/stream_server.h index 05b1a8b7..f0cf5302 100644 --- a/services/sensor/include/stream_server.h +++ b/services/sensor/include/stream_server.h @@ -37,7 +37,7 @@ public: int32_t AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenType, int32_t &serverFd, int32_t &clientFd); protected: - bool AddSession(SessionPtr ses); + bool AddSession(SessionPtr sess); void DelSession(int32_t pid); std::mutex sessionMutex_; std::map idxPidMap_; diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index b125383c..08770df0 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -425,7 +425,7 @@ ErrCode SensorService::SuspendSensors(int32_t pid) SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } - return sensorPowerPolicy_.SuspendSensors(pid); + return PowerPolicy.SuspendSensors(pid); } ErrCode SensorService::ResumeSensors(int32_t pid) @@ -435,7 +435,7 @@ ErrCode SensorService::ResumeSensors(int32_t pid) SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } - return sensorPowerPolicy_.ResumeSensors(pid); + return PowerPolicy.ResumeSensors(pid); } ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector &activeInfoList) @@ -445,7 +445,7 @@ ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector &a SEN_HILOGE("Pid is invalid"); return CLIENT_PID_INVALID_ERR; } - activeInfoList = sensorPowerPolicy_.GetActiveInfoList(pid); + activeInfoList = PowerPolicy.GetActiveInfoList(pid); return ERR_OK; } @@ -502,7 +502,7 @@ void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid) SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); ActiveInfo activeInfo(pid, sensorId, sensorInfo.GetSamplingPeriodNs(), sensorInfo.GetMaxReportDelayNs()); - sensorPowerPolicy_.ReportActiveInfo(activeInfo, sessionList); + PowerPolicy.ReportActiveInfo(activeInfo, sessionList); } bool SensorService::RegisterPermCallback(int32_t sensorId) diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index ffecd5a3..51b1dbc0 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -47,12 +47,12 @@ bool StreamServer::SendMsg(int32_t fd, const NetPacket& pkt) SEN_HILOGE("Fd is invalid"); return false; } - auto ses = GetSession(fd); - if (ses == nullptr) { - SEN_HILOGE("Fd not found, The message was discarded."); + auto sess = GetSession(fd); + if (sess == nullptr) { + SEN_HILOGE("sess is nullptr"); return false; } - return ses->SendMsg(pkt); + return sess->SendMsg(pkt); } void StreamServer::Multicast(const std::vector& fdList, const NetPacket& pkt) @@ -117,19 +117,19 @@ int32_t StreamServer::AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenT static constexpr size_t bufferSize = 32 * 1024; SessionPtr sess = nullptr; if (setsockopt(serverFd, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt serverFd buffer size failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt send buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } if (setsockopt(serverFd, SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt serverFd buffer size failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt recv buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } if (setsockopt(clientFd, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt clientFd buffer size failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt send buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } if (setsockopt(clientFd, SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt clientFd buffer size failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt recv buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } sess = std::make_shared("", serverFd, uid, pid); @@ -148,29 +148,28 @@ CLOSE_SOCK: return ERROR; } -bool StreamServer::AddSession(SessionPtr ses) +bool StreamServer::AddSession(SessionPtr sess) { CALL_LOG_ENTER; - CHKPF(ses); - auto fd = ses->GetFd(); + CHKPF(sess); + auto fd = sess->GetFd(); if (fd < 0) { SEN_HILOGE("Fd is Invalid"); return false; } - auto pid = ses->GetPid(); + auto pid = sess->GetPid(); if (pid <= 0) { - SEN_HILOGE("Get process failed"); + SEN_HILOGE("Pid is invalid"); return false; } + std::lock_guard sessionLock(sessionMutex_); if (sessionsMap_.size() > MAX_SESSON_ALARM) { SEN_HILOGE("Too many clients. Warning Value:%{public}zu, Current Value:%{public}zu", MAX_SESSON_ALARM, sessionsMap_.size()); return false; } - DelSession(pid); - std::lock_guard sessionLock(sessionMutex_); idxPidMap_[pid] = fd; - sessionsMap_[fd] = ses; + sessionsMap_[fd] = sess; return true; } @@ -180,6 +179,7 @@ void StreamServer::DelSession(int32_t pid) std::lock_guard sessionLock(sessionMutex_); auto pidIt = idxPidMap_.find(pid); if (pidIt == idxPidMap_.end()) { + SEN_HILOGW("Pid session not exist"); return; } int32_t fd = pidIt->second; @@ -189,7 +189,7 @@ void StreamServer::DelSession(int32_t pid) sessionsMap_.erase(fdIt); } if (fd >= 0) { - auto rf = close(fd); + int32_t rf = close(fd); if (rf != 0) { SEN_HILOGE("Socket fd close failed, rf:%{public}d, errno:%{public}d", rf, errno); } -- Gitee From e1e3164e1368662e224b941cecc020bea839a739 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 8 May 2023 07:17:53 +0000 Subject: [PATCH 46/53] update Signed-off-by: hui1975 Change-Id: If3d91b5640aa2078978be3a90d2e7dd7b9a8c7ae --- services/sensor/include/sensor_service.h | 1 - services/sensor/src/sensor_service.cpp | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/services/sensor/include/sensor_service.h b/services/sensor/include/sensor_service.h index 2cc753c1..841b495e 100644 --- a/services/sensor/include/sensor_service.h +++ b/services/sensor/include/sensor_service.h @@ -98,7 +98,6 @@ private: SensorHdiConnection &sensorHdiConnection_ = SensorHdiConnection::GetInstance(); ClientInfo &clientInfo_ = ClientInfo::GetInstance(); SensorManager &sensorManager_ = SensorManager::GetInstance(); - using PowerPolicy = SensorPowerPolicy::GetInstance(); sptr sensorDataProcesser_ = nullptr; sptr reportDataCallback_ = nullptr; std::mutex uidLock_; diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index 08770df0..de889a6f 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -40,6 +40,8 @@ constexpr int64_t MAX_EVENT_COUNT = 1000; std::atomic_bool g_isRegister = false; } // namespace +#define PowerPolicy SensorPowerPolicy::GetInstance() + REGISTER_SYSTEM_ABILITY_BY_ID(SensorService, SENSOR_SERVICE_ABILITY_ID, true); SensorService::SensorService(int32_t systemAbilityId, bool runOnCreate) -- Gitee From 7ccb4800c583dfdc1b36a481d5f7123d96303856 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 8 May 2023 08:36:52 +0000 Subject: [PATCH 47/53] update Signed-off-by: hui1975 Change-Id: I5d2df1744d9d7002f3e579f5b8b14e66db5175f2 --- services/sensor/src/stream_server.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/services/sensor/src/stream_server.cpp b/services/sensor/src/stream_server.cpp index 51b1dbc0..95eddf68 100644 --- a/services/sensor/src/stream_server.cpp +++ b/services/sensor/src/stream_server.cpp @@ -105,31 +105,31 @@ int32_t StreamServer::AddSocketPairInfo(int32_t uid, int32_t pid, int32_t tokenT CALL_LOG_ENTER; int32_t sockFds[2] = { -1 }; if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockFds) != 0) { - SEN_HILOGE("Call socketpair failed, errno:%{public}d", errno); + SEN_HILOGE("Socketpair failed, errno:%{public}d", errno); return ERROR; } serverFd = sockFds[0]; clientFd = sockFds[1]; if (serverFd < 0 || clientFd < 0) { - SEN_HILOGE("Call socketpair failed, errno:%{public}d", errno); + SEN_HILOGE("ServerFd or clientFd is invalid"); return ERROR; } static constexpr size_t bufferSize = 32 * 1024; SessionPtr sess = nullptr; if (setsockopt(serverFd, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt send buffer size failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt serverFd send buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } if (setsockopt(serverFd, SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt recv buffer size failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt serverFd recv buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } if (setsockopt(clientFd, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt send buffer size failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt clientFd send buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } if (setsockopt(clientFd, SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize)) != 0) { - SEN_HILOGE("Setsockopt recv buffer size failed, errno: %{public}d", errno); + SEN_HILOGE("Setsockopt clientFd recv buffer size failed, errno: %{public}d", errno); goto CLOSE_SOCK; } sess = std::make_shared("", serverFd, uid, pid); @@ -164,8 +164,7 @@ bool StreamServer::AddSession(SessionPtr sess) } std::lock_guard sessionLock(sessionMutex_); if (sessionsMap_.size() > MAX_SESSON_ALARM) { - SEN_HILOGE("Too many clients. Warning Value:%{public}zu, Current Value:%{public}zu", - MAX_SESSON_ALARM, sessionsMap_.size()); + SEN_HILOGE("Too many clients, size:%{public}zu", sessionsMap_.size()); return false; } idxPidMap_[pid] = fd; -- Gitee From ea5423ed30acb4feaec56c61bf43beee6af41df5 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Tue, 9 May 2023 07:15:00 +0000 Subject: [PATCH 48/53] update Signed-off-by: hui1975 Change-Id: I8e099bda79296c510d3374fc1cc0760d80568084 --- services/sensor/src/sensor_power_policy.cpp | 48 +++++---------------- services/sensor/src/sensor_service.cpp | 1 - 2 files changed, 11 insertions(+), 38 deletions(-) diff --git a/services/sensor/src/sensor_power_policy.cpp b/services/sensor/src/sensor_power_policy.cpp index 1fd09f52..b466037f 100644 --- a/services/sensor/src/sensor_power_policy.cpp +++ b/services/sensor/src/sensor_power_policy.cpp @@ -41,28 +41,26 @@ ErrCode SensorPowerPolicy::SuspendSensors(int32_t pid) CALL_LOG_ENTER; std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); if (sensorIdList.empty()) { - // 如果clientMap中没有当前pid的sensor信息,说明不需要休眠,直接返回失败 - SEN_HILOGE("Suspend sensor failed, sensorIdList is empty, pid:%{public}d", pid); - return SUSPEND_ERR; + SEN_HILOGW("SensorIdList is empty, pid not enable sensor or all sensor have bean suspend"); + return ERR_OK; } std::lock_guard pidSensorInfoLock(pidSensorInfoMutex_); auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); if (pidSensorInfoIt != pidSensorInfoMap_.end()) { - // policy中有数据,clientMap中也有数据 + SEN_HILOGI("Pid already call suspend, but some sensors suspend failed, suspend these sensors again"); std::unordered_map sensorInfoMap = pidSensorInfoIt->second; if (!Suspend(pid, sensorIdList, sensorInfoMap)) { - SEN_HILOGE("Suspend part sensors, but some failed"); - return SUSPEND_ERR; + SEN_HILOGE("Suspend last failed sensors, but some failed"); + return DISABLE_SENSOR_ERR; } return ERR_OK; } - // 数据全部保存在clientMap中 std::unordered_map sensorInfoMap; auto isAllSuspend = Suspend(pid, sensorIdList, sensorInfoMap); pidSensorInfoMap_.insert(std::make_pair(pid, sensorInfoMap)); if (!isAllSuspend) { SEN_HILOGE("Suspend all sensors, but some failed"); - return SUSPEND_ERR; + return DISABLE_SENSOR_ERR; } return ERR_OK; } @@ -77,29 +75,16 @@ bool SensorPowerPolicy::Suspend(int32_t pid, std::vector &sensorIdList, SEN_HILOGD("Current sensor is pedometer detection or pedometer, can not suspend"); continue; } - // 检查当前sensorId是否在当前pid的白名单中,如果在,continue跳过 auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { SEN_HILOGD("Other client is using this sensor now, cannot suspend"); - sensorInfo.SetSensorState(false); // 休眠成功,将状态置为false,保存到policy中 sensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); continue; } - - bool flag = false; - for (int32_t i = 0; i < 3; ++i) { - if (sensorHdiConnection_.DisableSensor(sensorId) == ERR_OK) { - flag = true; - break; - } - sleep(); - } - - if (flag == true) { - sensorInfo.SetSensorState(false); // 休眠成功,将状态置为false - } else { + if (sensorHdiConnection_.DisableSensor(sensorId) != ERR_OK) { + SEN_HILOGE("Disable sensor failed, sensorId:%{public}d", sensorId); isAllSuspend = false; - sensorInfo.SetSensorState(true); // 休眠失败,将状态置为true + continue; } sensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); sensorManager_.AfterDisableSensor(sensorId); @@ -114,7 +99,7 @@ ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); if (pidSensorInfoIt == pidSensorInfoMap_.end()) { SEN_HILOGE("Pid not have suspend sensors"); - return RESUME_ERR; + return ERROR; } bool isAllResume = true; std::unordered_map sensorInfoMap = pidSensorInfoIt->second; @@ -122,8 +107,6 @@ ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) int32_t sensorId = sensorIt->first; int64_t samplingPeriodNs = sensorIt->second.GetSamplingPeriodNs(); int64_t maxReportDelayNs = sensorIt->second.GetMaxReportDelayNs(); - bool sensorState = sensorIt->second.GetSensorState(); - if (!Resume(pid, sensorId, samplingPeriodNs, maxReportDelayNs)) { SEN_HILOGE("Resume sensor failed. sensorId:%{public}d", sensorId); isAllResume = false; @@ -134,7 +117,7 @@ ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) } if (!isAllResume) { SEN_HILOGE("Some sensor resume failed"); - return RESUME_ERR; + return ENABLE_SENSOR_ERR; } pidSensorInfoMap_.erase(pidSensorInfoIt); return ERR_OK; @@ -150,23 +133,14 @@ bool SensorPowerPolicy::Resume(int32_t pid, int32_t sensorId, int64_t samplingPe return false; } if (clientInfo_.GetSensorState(sensorId)) { - //当前sensor已经被其他进程打开 SEN_HILOGD("Sensor is enable, sensorId:%{public}d", sensorId); auto ret = RestoreSensorInfo(pid, sensorId, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { SEN_HILOGE("Restore sensor info failed, ret:%{public}d", ret); - // 给clientMap中恢复信息失败 return false; } return true; } - // 当前sensor没有被其他进程打开 - // 如果 sensorstate == false, 说明suspend成功, 而且没被其他进程打开 - // 1. 给clientMap中恢复信息 - // 2. 三次重试打开传感器,打开失败时删除clientMap中恢复的信息 - // 如果 sensorstate == true, 说明suspend失败,而且没有被其他进程打开。 但此时sensor可能是打开状态也可能是关闭状态 - - auto ret = RestoreSensorInfo(pid, sensorId, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { SEN_HILOGE("Restore sensor info failed, ret:%{public}d", ret); diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index b36b3bc2..c5f30e6e 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -329,7 +329,6 @@ ErrCode SensorService::DestroySensorChannel(sptr sensorClient) const int32_t clientPid = GetCallingPid(); if (clientPid < 0) { SEN_HILOGE("clientPid is invalid, clientPid:%{public}d", clientPid); - return CLIENT_PID_INVALID_ERR; } std::lock_guard serviceLock(serviceLock_); -- Gitee From e5336dea779fdba7af69766d43a37b7b853e1e2b Mon Sep 17 00:00:00 2001 From: hui1975 Date: Tue, 9 May 2023 07:23:10 +0000 Subject: [PATCH 49/53] update Signed-off-by: hui1975 Change-Id: I9039080004bcedb96215bdd01c480e08948fd8f9 --- services/sensor/src/sensor_service.cpp | 2 -- utils/common/include/sensors_errors.h | 2 -- 2 files changed, 4 deletions(-) diff --git a/services/sensor/src/sensor_service.cpp b/services/sensor/src/sensor_service.cpp index c5f30e6e..7146faf6 100644 --- a/services/sensor/src/sensor_service.cpp +++ b/services/sensor/src/sensor_service.cpp @@ -40,8 +40,6 @@ constexpr int64_t MAX_EVENT_COUNT = 1000; std::atomic_bool g_isRegister = false; } // namespace -#define PowerPolicy SensorPowerPolicy::GetInstance() - REGISTER_SYSTEM_ABILITY_BY_ID(SensorService, SENSOR_SERVICE_ABILITY_ID, true); SensorService::SensorService(int32_t systemAbilityId, bool runOnCreate) diff --git a/utils/common/include/sensors_errors.h b/utils/common/include/sensors_errors.h index ed25743f..43edceab 100644 --- a/utils/common/include/sensors_errors.h +++ b/utils/common/include/sensors_errors.h @@ -92,8 +92,6 @@ enum { SET_SENSOR_MODE_ERR = READ_PARCEL_ERR + 1, SET_SENSOR_OPTION_ERR = SET_SENSOR_MODE_ERR + 1, REGIST_CALLBACK_ERR = SET_SENSOR_OPTION_ERR + 1, - SUSPEND_ERR = REGIST_CALLBACK_ERR + 1; - RESUME_ERR = SUSPEND_ERR; }; // Error code for Sensor utils -- Gitee From a632da8485a717e951dc3b804587f343932733d0 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Wed, 10 May 2023 09:13:31 +0000 Subject: [PATCH 50/53] update Signed-off-by: hui1975 Change-Id: I0b6c437b3ddf315e14cdd3807da27a48498139c4 --- frameworks/native/sensor/include/fd_listener.h | 4 ++-- .../native/sensor/include/sensor_agent_proxy.h | 4 ++-- .../sensor/include/sensor_service_client.h | 4 ++-- .../native/sensor/src/sensor_agent_proxy.cpp | 8 ++++---- .../native/sensor/src/sensor_service_client.cpp | 4 ++-- .../native/sensor/src/sensor_service_proxy.cpp | 2 +- interfaces/native/include/sensor_agent.h | 4 ++-- interfaces/native/src/sensor_agent.cpp | 8 ++++---- .../native/test/unittest/sensor_power_test.cpp | 16 ++++++++-------- services/sensor/src/sensor_service_stub.cpp | 4 ++-- 10 files changed, 29 insertions(+), 29 deletions(-) diff --git a/frameworks/native/sensor/include/fd_listener.h b/frameworks/native/sensor/include/fd_listener.h index 76b45777..e8e2ad85 100644 --- a/frameworks/native/sensor/include/fd_listener.h +++ b/frameworks/native/sensor/include/fd_listener.h @@ -25,7 +25,7 @@ namespace Sensors { class FdListener : public AppExecFwk::FileDescriptorListener { public: FdListener() = default; - ~FdListener() override = default; + ~FdListener() = default; void OnReadable(int32_t fd) override; void OnShutdown(int32_t fd) override; void OnException(int32_t fd) override; @@ -33,7 +33,7 @@ public: DISALLOW_COPY_AND_MOVE(FdListener); private: - SensorDataChannel *channel_ = nullptr; + SensorDataChannel *channel_ = { nullptr }; }; } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/sensor/include/sensor_agent_proxy.h b/frameworks/native/sensor/include/sensor_agent_proxy.h index 4e36e6eb..97ee8910 100644 --- a/frameworks/native/sensor/include/sensor_agent_proxy.h +++ b/frameworks/native/sensor/include/sensor_agent_proxy.h @@ -46,8 +46,8 @@ public: int32_t SuspendSensors(int32_t pid) const; int32_t ResumeSensors(int32_t pid) const; int32_t GetSensorActiveInfos(int32_t pid, SensorActiveInfo **sensorActiveInfos, int32_t *count) const; - int32_t RegisterSensorActiveInfoCB(SensorActiveInfoCB callback) const; - int32_t UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback) const; + int32_t Register(SensorActiveInfoCB callback) const; + int32_t Unregister(SensorActiveInfoCB callback) const; private: int32_t CreateSensorDataChannel() const; diff --git a/frameworks/native/sensor/include/sensor_service_client.h b/frameworks/native/sensor/include/sensor_service_client.h index ea07be41..997ba793 100755 --- a/frameworks/native/sensor/include/sensor_service_client.h +++ b/frameworks/native/sensor/include/sensor_service_client.h @@ -48,8 +48,8 @@ public: int32_t SuspendSensors(int32_t pid); int32_t ResumeSensors(int32_t pid); int32_t GetActiveInfoList(int32_t pid, std::vector &activeInfoList); - int32_t RegisterSensorActiveInfoCB(SensorActiveInfoCB callback, sptr sensorDataChannel); - int32_t UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback); + int32_t Register(SensorActiveInfoCB callback, sptr sensorDataChannel); + int32_t Unregister(SensorActiveInfoCB callback); void ReceiveMessage(const char *buf, size_t size); void Disconnect(); diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index f8f72c7c..821f2453 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -408,21 +408,21 @@ int32_t SensorAgentProxy::GetSensorActiveInfos(int32_t pid, SensorActiveInfo **s return ERR_OK; } -int32_t SensorAgentProxy::RegisterSensorActiveInfoCB(SensorActiveInfoCB callback) const +int32_t SensorAgentProxy::Register(SensorActiveInfoCB callback) const { CHKPR(callback, OHOS::Sensors::ERROR); CHKPR(dataChannel_, INVALID_POINTER); - int32_t ret = SenClient.RegisterSensorActiveInfoCB(callback, dataChannel_); + int32_t ret = SenClient.Register(callback, dataChannel_); if (ret != ERR_OK) { SEN_HILOGE("Register sensor active info callback failed, ret:%{public}d", ret); } return ret; } -int32_t SensorAgentProxy::UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback) const +int32_t SensorAgentProxy::Unregister(SensorActiveInfoCB callback) const { CHKPR(callback, OHOS::Sensors::ERROR); - int32_t ret = SenClient.UnregisterSensorActiveInfoCB(callback); + int32_t ret = SenClient.Unregister(callback); if (ret != ERR_OK) { SEN_HILOGE("Unregister sensor active info callback failed, ret:%{public}d", ret); } diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index 8ad9c087..29d2ce2b 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -280,7 +280,7 @@ int32_t SensorServiceClient::GetActiveInfoList(int32_t pid, std::vector sensorDataChannel) +int32_t SensorServiceClient::Register(SensorActiveInfoCB callback, sptr sensorDataChannel) { CALL_LOG_ENTER; if (!isConnected_) { @@ -297,7 +297,7 @@ int32_t SensorServiceClient::RegisterSensorActiveInfoCB(SensorActiveInfoCB callb return ERR_OK; } -int32_t SensorServiceClient::UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback) +int32_t SensorServiceClient::Unregister(SensorActiveInfoCB callback) { CALL_LOG_ENTER; std::lock_guard activeInfoCBLock(activeInfoCBMutex_); diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 3dae4704..05967502 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -266,7 +266,7 @@ ErrCode SensorServiceProxy::CreateSocketChannel(sptr sensorClient } clientFd = reply.ReadFileDescriptor(); if (clientFd < 0) { - SEN_HILOGE("Invalid fd"); + SEN_HILOGE("Invalid fd, clientFd:%{public}d", clientFd); return ERROR; } return static_cast(ret); diff --git a/interfaces/native/include/sensor_agent.h b/interfaces/native/include/sensor_agent.h index 50b37f8c..9ca013e8 100755 --- a/interfaces/native/include/sensor_agent.h +++ b/interfaces/native/include/sensor_agent.h @@ -164,7 +164,7 @@ int32_t GetSensorActiveInfos(int32_t pid, SensorActiveInfo **sensorActiveInfos, * * @since 10 */ -int32_t RegisterSensorActiveInfoCB(SensorActiveInfoCB callback); +int32_t Register(SensorActiveInfoCB callback); /** * @brief 取消注册传感器打开信息上报函数 * @@ -173,7 +173,7 @@ int32_t RegisterSensorActiveInfoCB(SensorActiveInfoCB callback); * * @since 10 */ -int32_t UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback); +int32_t Unregister(SensorActiveInfoCB callback); #ifdef __cplusplus #if __cplusplus diff --git a/interfaces/native/src/sensor_agent.cpp b/interfaces/native/src/sensor_agent.cpp index 64b055a5..c81a7b01 100755 --- a/interfaces/native/src/sensor_agent.cpp +++ b/interfaces/native/src/sensor_agent.cpp @@ -195,14 +195,14 @@ int32_t GetSensorActiveInfos(int32_t pid, SensorActiveInfo **sensorActiveInfos, return ret; } -int32_t RegisterSensorActiveInfoCB(SensorActiveInfoCB callback) +int32_t Register(SensorActiveInfoCB callback) { const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); return SERVICE_EXCEPTION; } - int32_t ret = proxy->RegisterSensorActiveInfoCB(callback); + int32_t ret = proxy->Register(callback); if (ret != OHOS::ERR_OK) { SEN_HILOGE("Register sensor active Info callback failed, ret:%{public}d", ret); return NormalizeErrCode(ret); @@ -210,14 +210,14 @@ int32_t RegisterSensorActiveInfoCB(SensorActiveInfoCB callback) return ret; } -int32_t UnregisterSensorActiveInfoCB(SensorActiveInfoCB callback) +int32_t Unregister(SensorActiveInfoCB callback) { const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); return SERVICE_EXCEPTION; } - int32_t ret = proxy->UnregisterSensorActiveInfoCB(callback); + int32_t ret = proxy->Unregister(callback); if (ret != OHOS::ERR_OK) { SEN_HILOGE("Unregister sensor active info callback failed, ret:%{public}d", ret); return NormalizeErrCode(ret); diff --git a/interfaces/native/test/unittest/sensor_power_test.cpp b/interfaces/native/test/unittest/sensor_power_test.cpp index c0068e83..7ecc777d 100644 --- a/interfaces/native/test/unittest/sensor_power_test.cpp +++ b/interfaces/native/test/unittest/sensor_power_test.cpp @@ -135,7 +135,7 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_004, TestSize.Level1) // 注册接口异常用例 SEN_HILOGI("SensorPowerTest_004 in"); SensorActiveInfoCB callback = nullptr; - int32_t ret = RegisterSensorActiveInfoCB(callback); + int32_t ret = Register(callback); ASSERT_NE(ret, OHOS::Sensors::SUCCESS); } @@ -144,7 +144,7 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_005, TestSize.Level1) // 取消注册接口异常用例 SEN_HILOGI("SensorPowerTest_005 in"); SensorActiveInfoCB callback = nullptr; - int32_t ret = UnregisterSensorActiveInfoCB(callback); + int32_t ret = Unregister(callback); ASSERT_NE(ret, OHOS::Sensors::SUCCESS); } @@ -225,7 +225,7 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_008, TestSize.Level1) user.callback = SensorDataCallbackImpl; SensorActiveInfoCB callback = SensorActiveInfoCBImpl; - int32_t ret = RegisterSensorActiveInfoCB(callback); + int32_t ret = Register(callback); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); ret = SubscribeSensor(sensorId, &user); @@ -249,7 +249,7 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_008, TestSize.Level1) ret = UnsubscribeSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = UnregisterSensorActiveInfoCB(callback); + ret = Unregister(callback); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); } @@ -262,9 +262,9 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_009, TestSize.Level1) SensorActiveInfoCB callback = SensorActiveInfoCBImpl; SensorActiveInfoCB callback2 = SensorActiveInfoCBImpl2; - int32_t ret = RegisterSensorActiveInfoCB(callback); + int32_t ret = Register(callback); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = RegisterSensorActiveInfoCB(callback2); + ret = Register(callback2); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); ret = SubscribeSensor(sensorId, &user); @@ -288,9 +288,9 @@ HWTEST_F(SensorPowerTest, SensorPowerTest_009, TestSize.Level1) ret = UnsubscribeSensor(sensorId, &user); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = UnregisterSensorActiveInfoCB(callback); + ret = Unregister(callback); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); - ret = UnregisterSensorActiveInfoCB(callback2); + ret = Unregister(callback2); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); } } // namespace Sensors diff --git a/services/sensor/src/sensor_service_stub.cpp b/services/sensor/src/sensor_service_stub.cpp index f1b97994..8835e53a 100755 --- a/services/sensor/src/sensor_service_stub.cpp +++ b/services/sensor/src/sensor_service_stub.cpp @@ -119,7 +119,7 @@ ErrCode SensorServiceStub::GetAllSensorsInner(MessageParcel &data, MessageParcel { (void)data; std::vector sensors = GetSensorList(); - int32_t sensorCount = sensors.size(); + int32_t sensorCount = static_cast(sensors.size()); WRITEINT32(reply, sensorCount, WRITE_PARCEL_ERR); for (int32_t i = 0; i < sensorCount; ++i) { if (!sensors[i].Marshalling(reply)) { @@ -193,7 +193,7 @@ ErrCode SensorServiceStub::GetActiveInfoListInner(MessageParcel &data, MessagePa SEN_HILOGE("Get activeInfo list failed"); return ret; } - int32_t activeInfoCount = activeInfoList.size(); + int32_t activeInfoCount = static_cast(activeInfoList.size()); WRITEINT32(reply, activeInfoCount, WRITE_PARCEL_ERR); for (int32_t i = 0; i < activeInfoCount; ++i) { if (!activeInfoList[i].Marshalling(reply)) { -- Gitee From 31db23590eefbe791d22b8449bfbd07e7819efa7 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Thu, 11 May 2023 13:43:38 +0000 Subject: [PATCH 51/53] update Signed-off-by: hui1975 Change-Id: I9cd3f4ac7fb6cc0bf278b3be519231e2c6b3fd29 --- .../sensor/src/sensor_service_proxy.cpp | 29 +++++++++---------- services/sensor/src/sensor_service_stub.cpp | 16 +++++----- 2 files changed, 22 insertions(+), 23 deletions(-) diff --git a/frameworks/native/sensor/src/sensor_service_proxy.cpp b/frameworks/native/sensor/src/sensor_service_proxy.cpp index 05967502..a2be1a2b 100755 --- a/frameworks/native/sensor/src/sensor_service_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_service_proxy.cpp @@ -29,7 +29,7 @@ using namespace OHOS::HiviewDFX; namespace { constexpr HiLogLabel LABEL = { LOG_CORE, SENSOR_LOG_DOMAIN, "SensorServiceProxy" }; -constexpr int32_t MAX_SENSOR_COUNT = 200; +constexpr uint32_t MAX_SENSOR_COUNT = 200; } // namespace SensorServiceProxy::SensorServiceProxy(const sptr &impl) : IRemoteProxy(impl) @@ -101,21 +101,19 @@ std::vector SensorServiceProxy::GetSensorList() SEN_HILOGE("failed, ret:%{public}d", ret); return sensors; } - int32_t sensorCount; - if (!reply.ReadInt32(sensorCount)) { + size_t sensorCount; + if (!reply.ReadUint32(sensorCount)) { SEN_HILOGE("Parcel read failed"); return sensors; } - SEN_HILOGD("sensorCount:%{public}d", sensorCount); + SEN_HILOGD("sensorCount:%{public}zu", sensorCount); if (sensorCount > MAX_SENSOR_COUNT) { sensorCount = MAX_SENSOR_COUNT; } Sensor sensor; - for (int32_t i = 0; i < sensorCount; i++) { + for (size_t i = 0; i < sensorCount; ++i) { auto tmpSensor = sensor.Unmarshalling(reply); - if (tmpSensor == nullptr) { - continue; - } + CHKPC(tmpSensor); sensors.push_back(*tmpSensor); } return sensors; @@ -230,15 +228,16 @@ ErrCode SensorServiceProxy::GetActiveInfoList(int32_t pid, std::vector(ret); } - int32_t activeInfoCount; - READINT32(reply, activeInfoCount, READ_PARCEL_ERR); + size_t activeInfoCount; + READUINT32(reply, activeInfoCount, READ_PARCEL_ERR); + SEN_HILOGD("activeInfoCount:%{public}zu", activeInfoCount); + if (activeInfoCount > MAX_SENSOR_COUNT) { + activeInfoCount = MAX_SENSOR_COUNT; + } ActiveInfo activeInfo; - for (int32_t i = 0; i < activeInfoCount; ++i) { + for (size_t i = 0; i < activeInfoCount; ++i) { auto tmpActiveInfo = activeInfo.Unmarshalling(reply); - if (tmpActiveInfo == nullptr) { - SEN_HILOGE("Current activeInfo is nullptr, i:%{public}d", i); - continue; - } + CHKPC(tmpActiveInfo); activeInfoList.push_back(*tmpActiveInfo); } return static_cast(ret); diff --git a/services/sensor/src/sensor_service_stub.cpp b/services/sensor/src/sensor_service_stub.cpp index 8835e53a..1747fbcb 100755 --- a/services/sensor/src/sensor_service_stub.cpp +++ b/services/sensor/src/sensor_service_stub.cpp @@ -119,11 +119,11 @@ ErrCode SensorServiceStub::GetAllSensorsInner(MessageParcel &data, MessageParcel { (void)data; std::vector sensors = GetSensorList(); - int32_t sensorCount = static_cast(sensors.size()); - WRITEINT32(reply, sensorCount, WRITE_PARCEL_ERR); - for (int32_t i = 0; i < sensorCount; ++i) { + size_t sensorCount = sensors.size(); + WRITEUINT32(reply, sensorCount, WRITE_PARCEL_ERR); + for (size_t i = 0; i < sensorCount; ++i) { if (!sensors[i].Marshalling(reply)) { - SEN_HILOGE("Sensor %{public}d marshalling failed", i); + SEN_HILOGE("Sensor %{public}zu marshalling failed", i); return GET_SENSOR_LIST_ERR; } } @@ -193,11 +193,11 @@ ErrCode SensorServiceStub::GetActiveInfoListInner(MessageParcel &data, MessagePa SEN_HILOGE("Get activeInfo list failed"); return ret; } - int32_t activeInfoCount = static_cast(activeInfoList.size()); - WRITEINT32(reply, activeInfoCount, WRITE_PARCEL_ERR); - for (int32_t i = 0; i < activeInfoCount; ++i) { + size_t activeInfoCount = activeInfoList.size(); + WRITEUINT32(reply, activeInfoCount, WRITE_PARCEL_ERR); + for (size_t i = 0; i < activeInfoCount; ++i) { if (!activeInfoList[i].Marshalling(reply)) { - SEN_HILOGE("ActiveInfo %{public}d marshalling failed", i); + SEN_HILOGE("ActiveInfo %{public}zu marshalling failed", i); return WRITE_PARCEL_ERR; } } -- Gitee From 3084557f888f4f7d752ff923e0c37ad6dabad953 Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 15 May 2023 11:18:30 +0000 Subject: [PATCH 52/53] update Signed-off-by: hui1975 Change-Id: I678e56ba788c3bc405c641492aadb1fe102375ea --- .../sensor/include/sensor_data_channel.h | 10 ++++++---- frameworks/native/sensor/src/fd_listener.cpp | 20 +++++++++++++------ .../native/sensor/src/sensor_agent_proxy.cpp | 8 +++++--- .../native/sensor/src/sensor_data_channel.cpp | 18 +++++++++++++---- .../sensor/src/sensor_service_client.cpp | 16 ++++++++------- 5 files changed, 48 insertions(+), 24 deletions(-) diff --git a/frameworks/native/sensor/include/sensor_data_channel.h b/frameworks/native/sensor/include/sensor_data_channel.h index df6778d1..a0c3af46 100644 --- a/frameworks/native/sensor/include/sensor_data_channel.h +++ b/frameworks/native/sensor/include/sensor_data_channel.h @@ -28,10 +28,10 @@ namespace OHOS { namespace Sensors { typedef void (*DataChannelCB)(SensorEvent *events, int32_t num, void *data); +using ReceiveMessageFun = std::function; +using DisconnectFun = std::function; class SensorDataChannel : public SensorBasicDataChannel { public: - using ReceiveMessageFun = std::function; - using DisconnectFun = std::function; SensorDataChannel() = default; ~SensorDataChannel(); static int32_t HandleEvent(int32_t fd, int32_t events, void *data); @@ -45,8 +45,8 @@ public: void *privateData_ = nullptr; int32_t AddFdListener(int32_t fd, ReceiveMessageFun receiveMessage, DisconnectFun disconnect); int32_t DelFdListener(int32_t fd); - ReceiveMessageFun receiveMessage_; - DisconnectFun disconnect_; + ReceiveMessageFun GetReceiveMessageFun() const; + DisconnectFun GetDisconnectFun() const; private: static void ThreadProcessTask(SensorDataChannel *sensorChannel); @@ -56,6 +56,8 @@ private: static std::shared_ptr eventRunner_; static int32_t receiveFd_; std::unordered_set listenedFdSet_; + ReceiveMessageFun receiveMessage_; + DisconnectFun disconnect_; }; } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/sensor/src/fd_listener.cpp b/frameworks/native/sensor/src/fd_listener.cpp index 1a37a217..df6e1767 100644 --- a/frameworks/native/sensor/src/fd_listener.cpp +++ b/frameworks/native/sensor/src/fd_listener.cpp @@ -35,14 +35,16 @@ void FdListener::SetChannel(SensorDataChannel *channel) void FdListener::OnReadable(int32_t fd) { if (fd < 0) { - SEN_HILOGE("Invalid fd"); + SEN_HILOGE("Invalid fd, fd:%{public}d", fd); return; } char szBuf[MAX_PACKET_BUF_SIZE] = {}; for (size_t i = 0; i < MAX_RECV_LIMIT; i++) { ssize_t size = recv(fd, szBuf, MAX_PACKET_BUF_SIZE, MSG_DONTWAIT | MSG_NOSIGNAL); if (size > 0) { - channel_->receiveMessage_(szBuf, size); + CHKPV(channel_); + ReceiveMessageFun receiveMessage = channel_->GetReceiveMessageFun(); + receiveMessage(szBuf, size); } else if (size < 0) { if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) { SEN_HILOGW("Continue for errno EAGAIN|EINTR|EWOULDBLOCK, size:%{public}zu, errno:%{public}d", @@ -64,18 +66,24 @@ void FdListener::OnReadable(int32_t fd) void FdListener::OnShutdown(int32_t fd) { + CALL_LOG_ENTER; if (fd < 0) { - SEN_HILOGE("Invalid fd"); + SEN_HILOGE("Invalid fd, fd:%{public}d", fd); } - channel_->disconnect_(); + CHKPV(channel_); + DisconnectFun disconnect = channel_->GetDisconnectFun(); + disconnect(); } void FdListener::OnException(int32_t fd) { + CALL_LOG_ENTER; if (fd < 0) { - SEN_HILOGE("Invalid fd"); + SEN_HILOGE("Invalid fd, fd:%{public}d", fd); } - channel_->disconnect_(); + CHKPV(channel_); + DisconnectFun disconnect = channel_->GetDisconnectFun(); + disconnect(); } } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index 821f2453..2f28f85e 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -341,7 +341,7 @@ int32_t SensorAgentProxy::SuspendSensors(int32_t pid) const { CALL_LOG_ENTER; if (pid < 0) { - SEN_HILOGE("Pid is invalid"); + SEN_HILOGE("Pid is invalid, pid:%{public}d", pid); return PARAMETER_ERROR; } int32_t ret = SenClient.SuspendSensors(pid); @@ -355,7 +355,7 @@ int32_t SensorAgentProxy::ResumeSensors(int32_t pid) const { CALL_LOG_ENTER; if (pid < 0) { - SEN_HILOGE("Pid is invalid"); + SEN_HILOGE("Pid is invalid, pid:%{public}d", pid); return PARAMETER_ERROR; } int32_t ret = SenClient.ResumeSensors(pid); @@ -369,7 +369,7 @@ int32_t SensorAgentProxy::GetSensorActiveInfos(int32_t pid, SensorActiveInfo **s { CALL_LOG_ENTER; if (pid < 0) { - SEN_HILOGE("Pid is invalid"); + SEN_HILOGE("Pid is invalid, pid:%{public}d", pid); return PARAMETER_ERROR; } CHKPR(sensorActiveInfos, OHOS::Sensors::ERROR); @@ -387,6 +387,8 @@ int32_t SensorAgentProxy::GetSensorActiveInfos(int32_t pid, SensorActiveInfo **s } if (activeInfoList.empty()) { SEN_HILOGD("Active info list is empty"); + *sensorActiveInfos = nullptr; + *count = 0; return ERR_OK; } size_t activeInfoCount = activeInfoList.size(); diff --git a/frameworks/native/sensor/src/sensor_data_channel.cpp b/frameworks/native/sensor/src/sensor_data_channel.cpp index c148592a..6bfc7e8b 100644 --- a/frameworks/native/sensor/src/sensor_data_channel.cpp +++ b/frameworks/native/sensor/src/sensor_data_channel.cpp @@ -72,7 +72,7 @@ int32_t SensorDataChannel::InnerSensorDataChannel() } auto pairRet = listenedFdSet_.insert(receiveFd); if (!pairRet.second) { - SEN_HILOGE("ListenedFdSet insert fd fail"); + SEN_HILOGE("ListenedFdSet insert fd fail, fd:%{public}d", receiveFd); return ERROR; } return ERR_OK; @@ -103,12 +103,12 @@ int32_t SensorDataChannel::AddFdListener(int32_t fd, ReceiveMessageFun receiveMe listener->SetChannel(this); auto errCode = eventHandler_->AddFileDescriptorListener(fd, AppExecFwk::FILE_DESCRIPTOR_INPUT_EVENT, listener); if (errCode != ERR_OK) { - SEN_HILOGE("Add fd listener failed, errCode:%{public}u", errCode); + SEN_HILOGE("Add fd listener failed, fd:%{public}d, errCode:%{public}u", fd, errCode); return ERROR; } auto pairRet = listenedFdSet_.insert(fd); if (!pairRet.second) { - SEN_HILOGE("ListenedFdSet insert fd fail"); + SEN_HILOGE("ListenedFdSet insert fd fail, fd:%{public}d", fd); return ERROR; } return ERR_OK; @@ -121,7 +121,7 @@ int32_t SensorDataChannel::DelFdListener(int32_t fd) eventHandler_->RemoveFileDescriptorListener(fd); auto it = listenedFdSet_.find(fd); if (it == listenedFdSet_.end()) { - SEN_HILOGE("ListenedFdSet not find fd"); + SEN_HILOGE("ListenedFdSet not find fd, fd:%{public}d", fd); return ERROR; } listenedFdSet_.erase(it); @@ -131,5 +131,15 @@ int32_t SensorDataChannel::DelFdListener(int32_t fd) } return ERR_OK; } + +ReceiveMessageFun SensorDataChannel::GetReceiveMessageFun() const +{ + return receiveMessage_; +} + +DisconnectFun SensorDataChannel::GetDisconnectFun() const +{ + return disconnect_; +} } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index 29d2ce2b..e270f555 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -300,10 +300,12 @@ int32_t SensorServiceClient::Register(SensorActiveInfoCB callback, sptr activeInfoCBLock(activeInfoCBMutex_); - activeInfoCBSet_.erase(callback); - if (!activeInfoCBSet_.empty()) { - return ERR_OK; + { + std::lock_guard activeInfoCBLock(activeInfoCBMutex_); + activeInfoCBSet_.erase(callback); + if (!activeInfoCBSet_.empty()) { + return ERR_OK; + } } int32_t ret = InitServiceClient(); if (ret != ERR_OK) { @@ -374,7 +376,7 @@ void SensorServiceClient::Disconnect() CHKPV(dataChannel_); int32_t ret = dataChannel_->DelFdListener(fd_); if (ret != ERR_OK) { - SEN_HILOGE("Delete fd listener failed, ret:%{public}d", ret); + SEN_HILOGE("Delete fd listener failed, fd:%{public}d, ret:%{public}d", fd_, ret); } Close(); } @@ -392,7 +394,7 @@ int32_t SensorServiceClient::CreateSocketChannel() StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel"); ret = sensorServer_->CreateSocketChannel(sensorClientStub_, clientFd); FinishTrace(HITRACE_TAG_SENSORS); - if (!(ret == ERR_OK && clientFd >= 0)) { + if (ret != ERR_OK || clientFd < 0) { Close(); SEN_HILOGE("Create socket channel failed, ret:%{public}d", ret); return ret; @@ -402,7 +404,7 @@ int32_t SensorServiceClient::CreateSocketChannel() std::bind(&SensorServiceClient::ReceiveMessage, this, std::placeholders::_1, std::placeholders::_2), std::bind(&SensorServiceClient::Disconnect, this)) != ERR_OK) { Close(); - SEN_HILOGE("Add fd listener failed"); + SEN_HILOGE("Add fd listener failed, fd:%{public}d", fd_); return ERROR; } StartTrace(HITRACE_TAG_SENSORS, "EnableActiveInfoCB"); -- Gitee From 2bd242f0128b23f83bea385f856b2c32d9a9460d Mon Sep 17 00:00:00 2001 From: hui1975 Date: Mon, 15 May 2023 11:52:59 +0000 Subject: [PATCH 53/53] update Signed-off-by: hui1975 Change-Id: Icfbd52eaa0eefe794544f1f9be1d2b9f0c2696ce --- frameworks/native/sensor/src/fd_listener.cpp | 2 +- frameworks/native/sensor/src/sensor_agent_proxy.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frameworks/native/sensor/src/fd_listener.cpp b/frameworks/native/sensor/src/fd_listener.cpp index df6e1767..62ed78f7 100644 --- a/frameworks/native/sensor/src/fd_listener.cpp +++ b/frameworks/native/sensor/src/fd_listener.cpp @@ -57,7 +57,7 @@ void FdListener::OnReadable(int32_t fd) SEN_HILOGD("The service side disconnect with the client. size:0, count:%{public}zu, errno:%{public}d", i, errno); break; - } + } if (size < MAX_PACKET_BUF_SIZE) { break; } diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index 2f28f85e..cb169a5e 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -399,7 +399,7 @@ int32_t SensorAgentProxy::GetSensorActiveInfos(int32_t pid, SensorActiveInfo **s sensorActiveInfos_ = (SensorActiveInfo *)malloc(sizeof(SensorActiveInfo) * activeInfoCount); CHKPR(sensorActiveInfos_, ERROR); for (size_t i = 0; i < activeInfoCount; ++i) { - SensorActiveInfo *curActiveInfo= sensorActiveInfos_ + i; + SensorActiveInfo *curActiveInfo = sensorActiveInfos_ + i; curActiveInfo->pid = activeInfoList[i].GetPid(); curActiveInfo->sensorId = activeInfoList[i].GetSensorId(); curActiveInfo->samplingPeriodNs = activeInfoList[i].GetSamplingPeriodNs(); -- Gitee