diff --git a/bundle.json b/bundle.json index 10b1a0acf8cf7756113ff3764ca5d89a3250e4d2..969562920738a7e4a3b3e296ceacbb5c896f8ab6 100644 --- a/bundle.json +++ b/bundle.json @@ -10,7 +10,7 @@ "name": "sensor", "subsystem": "sensors", "syscap": ["SystemCapability.Sensors.Sensor", "SystemCapability.Sensors.Sensor.Lite"], - "features": [], + "features": ["sensor_rust_socket_ipc"], "adapted_system_type": [ "standard" ], "rom": "2048KB", "ram": "~4096KB", @@ -66,7 +66,9 @@ "//base/sensors/sensor/test/unittest/interfaces/kits:unittest", "//base/sensors/sensor/test/fuzztest/interfaces:fuzztest", "//base/sensors/sensor/test/unittest/interfaces/inner_api:unittest", - "//base/sensors/sensor/test/fuzztest/services:fuzztest" + "//base/sensors/sensor/test/fuzztest/services:fuzztest", + "//base/sensors/sensor/test/fuzztest/services:fuzztest", + "//base/sensors/sensor/test/unittest/coverage:unittest" ] } } diff --git a/frameworks/js/napi/BUILD.gn b/frameworks/js/napi/BUILD.gn index b6f97fdd62a3c0d30b1bed6d9ccb2d1ea1ae9ced..09fcc71c759f59890fa1ac85217bffe567ea17ae 100644 --- a/frameworks/js/napi/BUILD.gn +++ b/frameworks/js/napi/BUILD.gn @@ -37,7 +37,10 @@ ohos_shared_library("libsensor") { "src/sensor_napi_utils.cpp", "src/sensor_system_js.cpp", ] - deps = [ "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native" ] + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + ] external_deps = [ "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", diff --git a/frameworks/js/napi/include/async_callback_info.h b/frameworks/js/napi/include/async_callback_info.h index fe9b012a30b9b16cc65d1a5acf79805695df7c86..f60bbb9ea5cac582e72009e4e1fd1f525a4425d7 100644 --- a/frameworks/js/napi/include/async_callback_info.h +++ b/frameworks/js/napi/include/async_callback_info.h @@ -72,7 +72,7 @@ struct RationMatrixData { float inclinationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; }; -struct SensorData { +struct CallbackSensorData { int32_t sensorTypeId; uint32_t dataLength; float data[DATA_LENGTH]; @@ -86,7 +86,7 @@ struct ReserveData { }; union CallbackData { - SensorData sensorData; + CallbackSensorData sensorData; GeomagneticData geomagneticData; RationMatrixData rationMatrixData; ReserveData reserveData; @@ -130,6 +130,6 @@ public: private: }; -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS #endif // ASYNC_CALLBACK_INFO_H \ No newline at end of file diff --git a/frameworks/js/napi/src/sensor_js.cpp b/frameworks/js/napi/src/sensor_js.cpp index 07abdcf8f7711d6cd25147256e4063675efceace..afd5742ec236147ae9bae3aef0b96c7f44b6f90d 100644 --- a/frameworks/js/napi/src/sensor_js.cpp +++ b/frameworks/js/napi/src/sensor_js.cpp @@ -75,7 +75,7 @@ static bool copySensorData(sptr callbackInfo, SensorEvent *ev callbackInfo->data.sensorData.sensorAccuracy = event->option; CHKPF(event->data); if (event->dataLen < sizeof(float)) { - SEN_HILOGE("Event dataLen less than float size."); + SEN_HILOGE("Event dataLen less than float size"); return false; } auto data = reinterpret_cast(event->data); @@ -1442,5 +1442,5 @@ extern "C" __attribute__((constructor)) void RegisterModule(void) { napi_module_register(&_module); } -} // namespace Sensors -} // namespace OHOS \ No newline at end of file +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/BUILD.gn b/frameworks/native/BUILD.gn index d2e6af9dab513308a4e4ad39dc085d5b4ceb403d..46701a0184b71ef9636f046d00930344a67acdda 100644 --- a/frameworks/native/BUILD.gn +++ b/frameworks/native/BUILD.gn @@ -47,7 +47,7 @@ ohos_shared_library("libsensor_client") { "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", ] - if (rust_socket_ipc) { + if (sensor_rust_socket_ipc) { deps += [ "$SUBSYSTEM_DIR/rust/utils/socket_ipc_rust_ffi:sensor_rust_util_ffi" ] } diff --git a/frameworks/native/include/sensor_agent_proxy.h b/frameworks/native/include/sensor_agent_proxy.h index 702b43d35933f3d11a5b27b90e7b996a69236356..b5258f7da594da4b4559e2c6aa942647383d1033 100644 --- a/frameworks/native/include/sensor_agent_proxy.h +++ b/frameworks/native/include/sensor_agent_proxy.h @@ -42,6 +42,7 @@ public: int32_t UnsubscribeSensor(int32_t sensorId, const SensorUser *user); int32_t SetMode(int32_t sensorId, const SensorUser *user, int32_t mode); int32_t SetOption(int32_t sensorId, const SensorUser *user, int32_t option); + void SetIsChannelCreated(bool isChannelCreated); int32_t GetAllSensors(SensorInfo **sensorInfo, int32_t *count) const; int32_t SuspendSensors(int32_t pid); int32_t ResumeSensors(int32_t pid); @@ -56,7 +57,7 @@ private: int32_t DestroySensorDataChannel(); int32_t ConvertSensorInfos() const; void ClearSensorInfos() const; - std::set GetSubscribeUser(int32_t sensorId); + std::set GetSubscribeUserCallback(int32_t sensorId); static std::recursive_mutex subscribeMutex_; static std::mutex chanelMutex_; OHOS::sptr dataChannel_ = nullptr; @@ -68,6 +69,6 @@ private: }; #define SENSOR_AGENT_IMPL OHOS::DelayedSingleton::GetInstance() -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS #endif // endif SENSOR_PROXY_H \ No newline at end of file diff --git a/frameworks/native/include/sensor_service_client.h b/frameworks/native/include/sensor_service_client.h index 47033caebb36652932ef32f6c69f7c7d414e35f5..9657a1b38dcbcbe889adee9ea7100be446f9dd2a 100755 --- a/frameworks/native/include/sensor_service_client.h +++ b/frameworks/native/include/sensor_service_client.h @@ -60,6 +60,7 @@ private: void UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay); void DeleteSensorInfoItem(int32_t sensorId); int32_t CreateSocketChannel(); + void ReenableSensor(); std::mutex clientMutex_; sptr serviceDeathObserver_ = nullptr; sptr sensorServer_ = nullptr; @@ -74,6 +75,6 @@ private: std::mutex activeInfoCBMutex_; std::set activeInfoCBSet_; }; -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS #endif // SENSOR_SERVICE_CLIENT_H \ No newline at end of file diff --git a/frameworks/native/src/fd_listener.cpp b/frameworks/native/src/fd_listener.cpp index 4b8cbe1df1645dba1e690588588004653c428ce3..174fc169a68ef49dfca4c461b3a43bbddf8bd77a 100644 --- a/frameworks/native/src/fd_listener.cpp +++ b/frameworks/native/src/fd_listener.cpp @@ -28,7 +28,7 @@ namespace Sensors { using namespace OHOS::AppExecFwk; namespace { constexpr int32_t MAX_DATA_BUF_SIZE = 256; -} // namespace +} void FdListener::SetChannel(SensorDataChannel *channel) { diff --git a/frameworks/native/src/geomagnetic_field.cpp b/frameworks/native/src/geomagnetic_field.cpp index e0ac5c49a1ff8bf012d72a772cd84446b3cecb8a..5b96e7667c624dcb72f90111f6c1941c0df0c819 100644 --- a/frameworks/native/src/geomagnetic_field.cpp +++ b/frameworks/native/src/geomagnetic_field.cpp @@ -111,7 +111,7 @@ std::vector> polynomialsDerivative(GAUSSIAN_COEFFICIENT_DIMEN std::vector relativeRadiusPower(GAUSSIAN_COEFFICIENT_DIMENSION + 2); std::vector sinMLongitude(GAUSSIAN_COEFFICIENT_DIMENSION); std::vector cosMLongitude(GAUSSIAN_COEFFICIENT_DIMENSION); -} // namespace +} GeomagneticField::GeomagneticField(float latitude, float longitude, float altitude, int64_t timeMillis) { diff --git a/frameworks/native/src/sensor_agent_proxy.cpp b/frameworks/native/src/sensor_agent_proxy.cpp index 0cdfbe2d2f4b387943ab5374da6324dd4287ade8..eae2a02e29f1012fbb0951f593044b1a07ed8ad2 100644 --- a/frameworks/native/src/sensor_agent_proxy.cpp +++ b/frameworks/native/src/sensor_agent_proxy.cpp @@ -17,6 +17,7 @@ #include +#include "print_sensor_data.h" #include "securec.h" #include "sensor_errors.h" #include "sensor_service_client.h" @@ -48,7 +49,7 @@ SensorAgentProxy::~SensorAgentProxy() ClearSensorInfos(); } -std::set SensorAgentProxy::GetSubscribeUser(int32_t sensorId) +std::set SensorAgentProxy::GetSubscribeUserCallback(int32_t sensorId) { std::lock_guard subscribeLock(subscribeMutex_); auto iter = subscribeMap_.find(sensorId); @@ -56,7 +57,14 @@ std::set SensorAgentProxy::GetSubscribeUser(int32_t sensorId SEN_HILOGE("Sensor is not subscribed"); return {}; } - return {iter->second}; + std::set callback; + for (const auto &it : iter->second) { + auto ret = callback.insert(it->callback); + if (!ret.second) { + SEN_HILOGE("callback insert fail"); + } + } + return callback; } void SensorAgentProxy::HandleSensorData(SensorEvent *events, @@ -70,16 +78,22 @@ void SensorAgentProxy::HandleSensorData(SensorEvent *events, SensorEvent eventStream; for (int32_t i = 0; i < num; ++i) { eventStream = events[i]; - std::set users = GetSubscribeUser(eventStream.sensorTypeId); - for (const auto &user : users) { - CHKPV(user); - RecordSensorCallback fun = user->callback; - CHKPV(fun); - fun(&eventStream); + auto callbacks = GetSubscribeUserCallback(eventStream.sensorTypeId); + for (const auto &callback : callbacks) { + CHKPV(callback); + callback(&eventStream); + PrintSensorData::GetInstance().ControlSensorClientPrint(callback, eventStream); } } } +void SensorAgentProxy::SetIsChannelCreated(bool isChannelCreated) +{ + CALL_LOG_ENTER; + std::lock_guard chanelLock(chanelMutex_); + isChannelCreated_ = isChannelCreated; +} + int32_t SensorAgentProxy::CreateSensorDataChannel() { CALL_LOG_ENTER; @@ -245,6 +259,9 @@ int32_t SensorAgentProxy::SubscribeSensor(int32_t sensorId, const SensorUser *us if (!status.second) { SEN_HILOGD("User has been subscribed"); } + if (PrintSensorData::GetInstance().IsContinuousType(sensorId)) { + PrintSensorData::GetInstance().SavePrintUserInfo(user->callback); + } return OHOS::Sensors::SUCCESS; } @@ -278,6 +295,9 @@ int32_t SensorAgentProxy::UnsubscribeSensor(int32_t sensorId, const SensorUser * if (unsubscribeSet.empty()) { unsubscribeMap_.erase(sensorId); } + if (PrintSensorData::GetInstance().IsContinuousType(sensorId)) { + PrintSensorData::GetInstance().SavePrintUserInfo(user->callback); + } return OHOS::Sensors::SUCCESS; } diff --git a/frameworks/native/src/sensor_data_channel.cpp b/frameworks/native/src/sensor_data_channel.cpp index c54732956172a1599a34d6c7a71a8dc480497bfc..4a2bfc1315694e8883248c06dce6b28e6fed3fee 100644 --- a/frameworks/native/src/sensor_data_channel.cpp +++ b/frameworks/native/src/sensor_data_channel.cpp @@ -40,7 +40,7 @@ int32_t SensorDataChannel::RestoreSensorDataChannel() { CHKPR(dataCB_, SENSOR_NATIVE_REGSITER_CB_ERR); if (GetReceiveDataFd() != -1) { - SEN_HILOGW("Restore sensor data channel failed, please destroy sensor data channel first."); + SEN_HILOGW("Restore sensor data channel failed, please destroy sensor data channel first"); return SENSOR_CHANNEL_RESTORE_FD_ERR; } return InnerSensorDataChannel(); diff --git a/frameworks/native/src/sensor_service_client.cpp b/frameworks/native/src/sensor_service_client.cpp index 7d6ceeecaf068f56a755338116f88d5c5b636a71..7d50717bc1f7626ea68c81ef4031c5a0bb3126bf 100644 --- a/frameworks/native/src/sensor_service_client.cpp +++ b/frameworks/native/src/sensor_service_client.cpp @@ -24,6 +24,7 @@ #include "hisysevent.h" #include "hitrace_meter.h" #include "ipc_skeleton.h" +#include "sensor_agent_proxy.h" #include "sensor_errors.h" #include "sensor_service_proxy.h" #include "system_ability_definition.h" @@ -107,7 +108,6 @@ bool SensorServiceClient::IsValid(int32_t sensorId) int32_t ret = InitServiceClient(); if (ret != ERR_OK) { SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); - return false; } std::lock_guard clientLock(clientMutex_); if (sensorList_.empty()) { @@ -218,6 +218,23 @@ int32_t SensorServiceClient::DestroyDataChannel() return ret; } +void SensorServiceClient::ReenableSensor() +{ + CALL_LOG_ENTER; + std::lock_guard mapLock(mapMutex_); + for (const auto &it : sensorInfoMap_) { + if (sensorServer_ != nullptr) { + sensorServer_->EnableSensor(it.first, it.second.GetSamplingPeriodNs(), it.second.GetMaxReportDelayNs()); + } + } + if (!isConnected_) { + SEN_HILOGD("Previous socket channel status is false, not need retry creat socket channel"); + return; + } + Disconnect(); + CreateSocketChannel(); +} + void SensorServiceClient::ProcessDeathObserver(const wptr &object) { CALL_LOG_ENTER; @@ -227,7 +244,6 @@ void SensorServiceClient::ProcessDeathObserver(const wptr &object SEN_HILOGI("dataChannel_ is nullptr"); { std::lock_guard clientLock(clientMutex_); - sensorList_.clear(); sensorServer_ = nullptr; } if (InitServiceClient() != ERR_OK) { @@ -240,12 +256,12 @@ void SensorServiceClient::ProcessDeathObserver(const wptr &object dataChannel_->RestoreSensorDataChannel(); { std::lock_guard clientLock(clientMutex_); - sensorList_.clear(); sensorServer_ = nullptr; } if (InitServiceClient() != ERR_OK) { SEN_HILOGE("InitServiceClient failed"); dataChannel_->DestroySensorDataChannel(); + SENSOR_AGENT_IMPL->SetIsChannelCreated(false); return; } if (sensorServer_ != nullptr && sensorClientStub_ != nullptr) { @@ -256,18 +272,7 @@ void SensorServiceClient::ProcessDeathObserver(const wptr &object } } } - std::lock_guard mapLock(mapMutex_); - for (const auto &it : sensorInfoMap_) { - if (sensorServer_ != nullptr) { - sensorServer_->EnableSensor(it.first, it.second.GetSamplingPeriodNs(), it.second.GetMaxReportDelayNs()); - } - } - if (!isConnected_) { - SEN_HILOGD("Previous socket channel status is false, not need retry creat socket channel"); - return; - } - Disconnect(); - CreateSocketChannel(); + ReenableSensor(); } void SensorServiceClient::UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay) diff --git a/interfaces/kits/c/oh_sensor.h b/interfaces/kits/c/oh_sensor.h index 3c9b54ddf85220bdfe35af49a08ff63b2b3fa8a3..5b2718a99f972c65e7a5b6a363a887acd2fd5124 100644 --- a/interfaces/kits/c/oh_sensor.h +++ b/interfaces/kits/c/oh_sensor.h @@ -45,8 +45,10 @@ extern "C" { * @param infos - Double pointer to the information about all sensors on the device. * For details, see {@link Sensor_Info}. * @param count - Pointer to the number of sensors on the device. - * @return Returns SENSOR_SUCCESS if the operation is successful; - * returns an error code defined in {@link Sensor_Result} otherwise. + * @return Returns SENSOR_SUCCESS if the operation is successful; returns the following error code otherwise. + * {@link SENSOR_PARAMETER_ERROR} Parameter check failed. For example, the parameter is invalid, + * or the parameter type passed in is incorrect.\n + * {@link SENSOR_SERVICE_EXCEPTION} The sensor service is abnormal.\n * * @since 11 */ @@ -65,8 +67,11 @@ Sensor_Result OH_Sensor_GetInfos(Sensor_Info **infos, uint32_t *count); * For details, see {@link Sensor_SubscriptionAttribute}. * @param subscriber - Pointer to the subscriber information, which is used to specify the callback function for * reporting the sensor data. For details, see {@link Sensor_Subscriber}. - * @return Returns SENSOR_SUCCESS if the operation is successful; - * returns an error code defined in {@link Sensor_Result} otherwise. + * @return Returns SENSOR_SUCCESS if the operation is successful; returns the following error code otherwise. + * {@link SENSOR_PERMISSION_DENIED} Permission verification failed.\n + * {@link SENSOR_PARAMETER_ERROR} Parameter check failed. For example, the parameter is invalid, + * or the parameter type passed in is incorrect.\n + * {@link SENSOR_SERVICE_EXCEPTION} The sensor service is abnormal.\n * @permission ohos.permission.ACCELEROMETER or ohos.permission.GYROSCOPE or * ohos.permission.ACTIVITY_MOTION or ohos.permission.READ_HEALTH_DATA * @since 11 @@ -85,8 +90,11 @@ Sensor_Result OH_Sensor_Subscribe(const Sensor_SubscriptionId *id, * @param id - Pointer to the sensor subscription ID. For details, see {@link Sensor_SubscriptionId}. * @param subscriber - Pointer to the subscriber information, which is used to specify the callback function for * reporting the sensor data. For details, see {@link Sensor_Subscriber}. - * @return Returns SENSOR_SUCCESS if the operation is successful; - * returns an error code defined in {@link Sensor_Result} otherwise. + * @return Returns SENSOR_SUCCESS if the operation is successful; returns the following error code otherwise. + * {@link SENSOR_PERMISSION_DENIED} Permission verification failed.\n + * {@link SENSOR_PARAMETER_ERROR} Parameter check failed. For example, the parameter is invalid, + * or the parameter type passed in is incorrect.\n + * {@link SENSOR_SERVICE_EXCEPTION} The sensor service is abnormal.\n * @permission ohos.permission.ACCELEROMETER or ohos.permission.GYROSCOPE or * ohos.permission.ACTIVITY_MOTION or ohos.permission.READ_HEALTH_DATA * diff --git a/interfaces/kits/c/oh_sensor_type.h b/interfaces/kits/c/oh_sensor_type.h index e0ab040e90cae5eb0224b1267f3dbc1b33515cfe..82fcd02ffc6e03641eba51e7bc501f8fc3f98b11 100644 --- a/interfaces/kits/c/oh_sensor_type.h +++ b/interfaces/kits/c/oh_sensor_type.h @@ -91,11 +91,21 @@ typedef enum Sensor_Type { * @since 11 */ SENSOR_TYPE_GRAVITY = 257, + /** + * Linear acceleration sensor. + * @since 13 + */ + SENSOR_TYPE_LINEAR_ACCELERATION = 258, /** * Rotation vector sensor. * @since 11 */ SENSOR_TYPE_ROTATION_VECTOR = 259, + /** + * Game rotation vector sensor. + * @since 13 + */ + SENSOR_TYPE_GAME_ROTATION_VECTOR = 262, /** * Pedometer detection sensor. * @since 11 @@ -120,23 +130,23 @@ typedef enum Sensor_Type { */ typedef enum Sensor_Result { /** - * The operation is successful. + * @error The operation is successful. * @since 11 */ SENSOR_SUCCESS = 0, /** - * Permission verification failed. + * @error Permission verification failed. * @since 11 */ SENSOR_PERMISSION_DENIED = 201, /** - * Parameter check failed. For example, a mandatory parameter is not passed in, + * @error Parameter check failed. For example, a mandatory parameter is not passed in, * or the parameter type passed in is incorrect. * @since 11 */ SENSOR_PARAMETER_ERROR = 401, /** - * The sensor service is abnormal. + * @error The sensor service is abnormal. * @since 11 */ SENSOR_SERVICE_EXCEPTION = 14500101, @@ -277,35 +287,35 @@ typedef struct Sensor_Event Sensor_Event; /** * @brief Obtains the sensor type. * - * @param Sensor_Event - Pointer to the sensor data information. + * @param sensorEvent - Pointer to the sensor data information. * @param sensorType - Pointer to the sensor type. * @return Returns SENSOR_SUCCESS if the operation is successful; * returns an error code defined in {@link Sensor_Result} otherwise. * @since 11 */ -int32_t OH_SensorEvent_GetType(Sensor_Event* Sensor_Event, Sensor_Type *sensorType); +int32_t OH_SensorEvent_GetType(Sensor_Event* sensorEvent, Sensor_Type *sensorType); /** * @brief Obtains the timestamp of sensor data. * - * @param Sensor_Event - Pointer to the sensor data information. + * @param sensorEvent - Pointer to the sensor data information. * @param timestamp - Pointer to the timestamp. * @return Returns SENSOR_SUCCESS if the operation is successful; * returns an error code defined in {@link Sensor_Result} otherwise. * @since 11 */ -int32_t OH_SensorEvent_GetTimestamp(Sensor_Event* Sensor_Event, int64_t *timestamp); +int32_t OH_SensorEvent_GetTimestamp(Sensor_Event* sensorEvent, int64_t *timestamp); /** * @brief Obtains the accuracy of sensor data. * - * @param Sensor_Event - Pointer to the sensor data information. + * @param sensorEvent - Pointer to the sensor data information. * @param accuracy - Pointer to the accuracy. * @return Returns SENSOR_SUCCESS if the operation is successful; * returns an error code defined in {@link Sensor_Result} otherwise. * @since 11 */ -int32_t OH_SensorEvent_GetAccuracy(Sensor_Event* Sensor_Event, Sensor_Accuracy *accuracy); +int32_t OH_SensorEvent_GetAccuracy(Sensor_Event* sensorEvent, Sensor_Accuracy *accuracy); /** * @brief Obtains sensor data. The data length and content depend on the sensor type. @@ -314,6 +324,9 @@ int32_t OH_SensorEvent_GetAccuracy(Sensor_Event* Sensor_Event, Sensor_Accuracy * * the x, y, and z axes of the device, respectively, in m/s2. * SENSOR_TYPE_GYROSCOPE: data[0], data[1], and data[2], indicating the angular velocity of rotation around * the x, y, and z axes of the device, respectively, in rad/s. + * SENSOR_TYPE_AMBIENT_LIGHT: data[0], indicating the ambient light intensity, in lux. Since api version 12, + * two additional data will be returned, where data[1] indicating the color temperature, in kelvin; data[2] + * indicating the infrared luminance, in cd/m2. * SENSOR_TYPE_AMBIENT_LIGHT: data[0], indicating the ambient light intensity, in lux. * SENSOR_TYPE_MAGNETIC_FIELD: data[0], data[1], and data[2], indicating the magnetic field strength around * the x, y, and z axes of the device, respectively, in μT. @@ -332,15 +345,20 @@ int32_t OH_SensorEvent_GetAccuracy(Sensor_Event* Sensor_Event, Sensor_Accuracy * * The value 1 means that the number of detected steps changes. * SENSOR_TYPE_PEDOMETER: data[0], indicating the number of steps a user has walked. * SENSOR_TYPE_HEART_RATE: data[0], indicating the heart rate value. + * SENSOR_TYPE_LINEAR_ACCELERATION: Supported from api version 13. data[0], data[1], and data[2], indicating the + * linear acceleration around the x, y, and z axes of the device, respectively, in m/s2. + * SENSOR_TYPE_GAME_ROTATION_VECTOR: Supported from api version 13. data[0], data[1] and data[2], indicating the + * rotation angles of a device around the x, y, and z axes, respectively, in degree. data[3] indicates the rotation + * vector. * - * @param Sensor_Event - Pointer to the sensor data information. + * @param sensorEvent - Pointer to the sensor data information. * @param data - Double pointer to the sensor data. * @param length - Pointer to the array length. * @return Returns SENSOR_SUCCESS if the operation is successful; * returns an error code defined in {@link Sensor_Result} otherwise. * @since 11 */ -int32_t OH_SensorEvent_GetData(Sensor_Event* Sensor_Event, float **data, uint32_t *length); +int32_t OH_SensorEvent_GetData(Sensor_Event* sensorEvent, float **data, uint32_t *length); /** * @brief Defines the sensor subscription ID, which uniquely identifies a sensor. @@ -371,7 +389,7 @@ int32_t OH_Sensor_DestroySubscriptionId(Sensor_SubscriptionId *id); * @brief Obtains the sensor type. * * @param id - Pointer to the sensor subscription ID. - * @param id - Pointer to the sensor type. + * @param sensorType - Pointer to the sensor type. * @return Returns SENSOR_SUCCESS if the operation is successful; * returns an error code defined in {@link Sensor_Result} otherwise. * @since 11 diff --git a/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs b/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs index a72de8fd503959e33d74e7d80d32f112342d966b..a56ef5dc5bfed0dde1f8edaf18a5a55d5b93a72c 100644 --- a/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs +++ b/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs @@ -176,7 +176,6 @@ pub unsafe extern "C" fn StreamBufferChkRWError(object: *const StreamBuffer) -> pub unsafe extern "C" fn StreamBufferGetErrorStatusRemark(object: *const StreamBuffer) -> *const c_char { info!(LOG_LABEL, "enter StreamBufferGetErrorStatusRemark"); if let Some(obj) = StreamBuffer::as_ref(object) { - // SAFETY: The Rust side creates a CString string and this function should be called only here obj.get_error_status_remark() } else { std::ptr::null() diff --git a/sensor.gni b/sensor.gni index 4306a82493993915a47e402827d6bb0d3a5e6be7..addc8d5221b745b3a961df3d23d9f203ebfe6ca5 100644 --- a/sensor.gni +++ b/sensor.gni @@ -14,7 +14,7 @@ import("//build/ohos.gni") declare_args() { - rust_socket_ipc = false + sensor_rust_socket_ipc = false } SUBSYSTEM_DIR = "//base/sensors/sensor" @@ -23,7 +23,7 @@ FUZZ_MODULE_OUT_PATH = "sensor/sensor" sensor_default_defines = [] -if (rust_socket_ipc) { +if (sensor_rust_socket_ipc) { sensor_default_defines += [ "OHOS_BUILD_ENABLE_RUST" ] } diff --git a/services/BUILD.gn b/services/BUILD.gn index f8b346c3af3103a89be453c46e2d749a19cb9b88..e2bca24f62e243491ff1caa5b6fb9a8ac66c39ac 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -49,7 +49,7 @@ ohos_shared_library("libsensor_service") { "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", ] - if (rust_socket_ipc) { + if (sensor_rust_socket_ipc) { deps += [ "$SUBSYSTEM_DIR/rust/utils/socket_ipc_rust_ffi:sensor_rust_util_ffi" ] } @@ -63,6 +63,7 @@ ohos_shared_library("libsensor_service") { "hitrace:hitrace_meter", "ipc:ipc_single", "safwk:system_ability_fwk", + "samgr:samgr_proxy", ] if (sensor_memmgr_enable) { @@ -137,7 +138,7 @@ ohos_static_library("libsensor_service_static") { "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", ] - if (rust_socket_ipc) { + if (sensor_rust_socket_ipc) { deps += [ "$SUBSYSTEM_DIR/rust/utils/socket_ipc_rust_ffi:sensor_rust_util_ffi" ] } @@ -151,6 +152,7 @@ ohos_static_library("libsensor_service_static") { "hitrace:hitrace_meter", "ipc:ipc_single", "safwk:system_ability_fwk", + "samgr:samgr_proxy", ] if (sensor_memmgr_enable) { diff --git a/services/hdi_connection/adapter/include/sensor_event_callback.h b/services/hdi_connection/adapter/include/sensor_event_callback.h index f1c62ff6733f7e42c441f660c70a824c516a8edd..33a72dbbf1d14941b02a7ab6db875aed6ea7a4e5 100644 --- a/services/hdi_connection/adapter/include/sensor_event_callback.h +++ b/services/hdi_connection/adapter/include/sensor_event_callback.h @@ -30,14 +30,7 @@ class SensorEventCallback : public ISensorCallback { public: virtual ~SensorEventCallback() {} int32_t OnDataEvent(const HdfSensorEvents &event) override; -private: - void ControlSensorPrint(const SensorData &sensorData); - void PrintSensorData(const SensorData &sensorData); - int32_t GetDataDimension(int32_t sensorId); - int64_t postureLastTs_ = 0; - int64_t ambientLightLastTs_ = 0; - int64_t magneticFieldLastTs_ = 0; }; -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS #endif // SENSOR_EVENT_CALLBACK_H diff --git a/services/hdi_connection/adapter/src/hdi_connection.cpp b/services/hdi_connection/adapter/src/hdi_connection.cpp index 977697dd6ac59848c8cad19142eacfcf46d418d9..c186868fe4eb2f4c7433c578b642cfe735f1224d 100644 --- a/services/hdi_connection/adapter/src/hdi_connection.cpp +++ b/services/hdi_connection/adapter/src/hdi_connection.cpp @@ -37,7 +37,7 @@ using OHOS::HDI::Sensor::V2_0::ISensorCallback; using OHOS::HDI::Sensor::V2_0::HdfSensorInformation; namespace { sptr g_sensorInterface = nullptr; -sptr g_eventCallback = nullptr; +sptr g_eventCallback = nullptr; std::map g_sensorBasicInfoMap; std::mutex g_sensorBasicInfoMutex; constexpr int32_t GET_HDI_SERVICE_COUNT = 25; @@ -55,8 +55,8 @@ int32_t HdiConnection::ConnectHdi() while (retry < GET_HDI_SERVICE_COUNT) { g_sensorInterface = ISensorInterface::Get(); if (g_sensorInterface != nullptr) { - SEN_HILOGI("Connect V2_0 hdi success"); - g_eventCallback = new (std::nothrow) SensorEventCallback(); + SEN_HILOGI("Connect v2_0 hdi success"); + g_eventCallback = new (std::nothrow) SensorEventCallback(); CHKPR(g_eventCallback, ERR_NO_INIT); RegisterHdiDeathRecipient(); return ERR_OK; @@ -193,7 +193,7 @@ int32_t HdiConnection::DestroyHdiConnection() SEN_HILOGE("Unregister is failed"); return ret; } - g_eventCallback = nullptr; + g_eventCallback = nullptr; UnregisterHdiDeathRecipient(); return ERR_OK; } @@ -220,6 +220,12 @@ void HdiConnection::UpdateSensorBasicInfo(int32_t sensorId, int64_t samplingPeri SensorBasicInfo sensorBasicInfo; sensorBasicInfo.SetSamplingPeriodNs(samplingPeriodNs); sensorBasicInfo.SetMaxReportDelayNs(maxReportDelayNs); + auto it = g_sensorBasicInfoMap.find(sensorId); + if (it != g_sensorBasicInfoMap.end()) { + if (g_sensorBasicInfoMap[sensorId].GetSensorState()) { + sensorBasicInfo.SetSensorState(true); + } + } g_sensorBasicInfoMap[sensorId] = sensorBasicInfo; } @@ -269,7 +275,7 @@ void HdiConnection::ProcessDeathObserver(const wptr &object) CHKPV(hdiService); CHKPV(hdiDeathObserver_); hdiService->RemoveDeathRecipient(hdiDeathObserver_); - g_eventCallback = nullptr; + g_eventCallback = nullptr; Reconnect(); } @@ -311,5 +317,5 @@ void HdiConnection::Reconnect() } } } -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS diff --git a/services/hdi_connection/adapter/src/sensor_event_callback.cpp b/services/hdi_connection/adapter/src/sensor_event_callback.cpp index 19c830f8c0206f3d5f00877d8be807e7711e785a..93a021f84eb8f94e9dedabd3b054563ce5a7ecd7 100644 --- a/services/hdi_connection/adapter/src/sensor_event_callback.cpp +++ b/services/hdi_connection/adapter/src/sensor_event_callback.cpp @@ -17,6 +17,7 @@ #include #include "hdi_connection.h" +#include "print_sensor_data.h" #include "sensor_agent_type.h" #include "sensor_errors.h" @@ -29,14 +30,6 @@ using namespace OHOS::HiviewDFX; namespace { std::unique_ptr HdiConnection_ = std::make_unique(); constexpr int32_t HEADPOSTURE_DATA_SIZE = 20; -constexpr int64_t LOG_INTERVAL = 60000000000; -enum { - ONE_DIMENSION = 1, - TWO_DIMENSION = 2, - THREE_DIMENSION = 3, - SEVEN_DIMENSION = 7, - DEFAULT_DIMENSION = 16 -}; const std::set g_sensorTypeTrigger = { SENSOR_TYPE_ID_PROXIMITY, SENSOR_TYPE_ID_DROP_DETECTION, @@ -87,71 +80,11 @@ int32_t SensorEventCallback::OnDataEvent(const HdfSensorEvents &event) sensorData.data[i] = event.data[i]; } } - ControlSensorPrint(sensorData); + PrintSensorData::GetInstance().ControlSensorHdiPrint(sensorData); std::unique_lock lk(ISensorHdiConnection::dataMutex_); (void)(reportDataCallback_->*(reportDataCb_))(&sensorData, reportDataCallback_); ISensorHdiConnection::dataCondition_.notify_one(); return ERR_OK; } - -void SensorEventCallback::ControlSensorPrint(const SensorData &sensorData) -{ - if (sensorData.sensorTypeId == SENSOR_TYPE_ID_HALL_EXT || sensorData.sensorTypeId == SENSOR_TYPE_ID_PROXIMITY - || sensorData.sensorTypeId == SENSOR_TYPE_ID_HALL) { - PrintSensorData(sensorData); - } - if ((sensorData.sensorTypeId == SENSOR_TYPE_ID_POSTURE) - && ((postureLastTs_ == 0) || (sensorData.timestamp - postureLastTs_ >= LOG_INTERVAL))) { - PrintSensorData(sensorData); - postureLastTs_ = sensorData.timestamp; - } - if ((sensorData.sensorTypeId == SENSOR_TYPE_ID_AMBIENT_LIGHT) - && ((ambientLightLastTs_ == 0) || (sensorData.timestamp - ambientLightLastTs_ >= LOG_INTERVAL))) { - PrintSensorData(sensorData); - ambientLightLastTs_ = sensorData.timestamp; - } - if ((sensorData.sensorTypeId == SENSOR_TYPE_ID_MAGNETIC_FIELD) - && ((magneticFieldLastTs_ == 0) || (sensorData.timestamp - magneticFieldLastTs_ >= LOG_INTERVAL))) { - PrintSensorData(sensorData); - magneticFieldLastTs_ = sensorData.timestamp; - } -} - -void SensorEventCallback::PrintSensorData(const SensorData &sensorData) -{ - std::string str; - str += "sensorId: " + std::to_string(sensorData.sensorTypeId) + ", "; - str += "timestamp: " + std::to_string(sensorData.timestamp) + ", "; - int32_t dataDim = GetDataDimension(sensorData.sensorTypeId); - auto data = reinterpret_cast(sensorData.data); - for (int32_t i = 0; i < dataDim; ++i) { - str.append(std::to_string(*data)); - if (i != dataDim - 1) { - str.append(", "); - } - ++data; - } - str.append("\n"); - SEN_HILOGI("SensorData: %{public}s", str.c_str()); -} - -int32_t SensorEventCallback::GetDataDimension(int32_t sensorId) -{ - switch (sensorId) { - case SENSOR_TYPE_ID_HALL: - case SENSOR_TYPE_ID_PROXIMITY: - return ONE_DIMENSION; - case SENSOR_TYPE_ID_HALL_EXT: - return TWO_DIMENSION; - case SENSOR_TYPE_ID_POSTURE: - return SEVEN_DIMENSION; - case SENSOR_TYPE_ID_AMBIENT_LIGHT: - case SENSOR_TYPE_ID_MAGNETIC_FIELD: - return THREE_DIMENSION; - default: - SEN_HILOGW("Unknown sensorId:%{public}d, size:%{public}d", sensorId, DEFAULT_DIMENSION); - return DEFAULT_DIMENSION; - } -} } // namespace Sensors } // namespace OHOS \ No newline at end of file diff --git a/services/include/sensor_service.h b/services/include/sensor_service.h index 67d9b4b0bcc613c17d5e60368254c82a3ed4e738..174aec478e8280fcc6ac4130e0ea2893bb9f1ffe 100644 --- a/services/include/sensor_service.h +++ b/services/include/sensor_service.h @@ -70,6 +70,7 @@ public: private: DISALLOW_COPY_AND_MOVE(SensorService); void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; + bool CheckParameter(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); class PermStateChangeCb : public Security::AccessToken::PermStateChangeCallbackCustomize { public: @@ -117,6 +118,6 @@ private: }; #define POWER_POLICY SensorPowerPolicy::GetInstance() -} // namespace Sensors -} // namespace OHOS -#endif // SENSOR_SERVICE_H +} // namespace Sensors +} // namespace OHOS +#endif // SENSOR_SERVICE_H diff --git a/services/src/sensor_data_processer.cpp b/services/src/sensor_data_processer.cpp index f67513209cc663c41c859e3e927860492026a60f..6ea5c6c8126d2965b4c146a6f27cc1d5ddc12965 100644 --- a/services/src/sensor_data_processer.cpp +++ b/services/src/sensor_data_processer.cpp @@ -274,9 +274,8 @@ int32_t SensorDataProcesser::ProcessEvents(sptr dataCallback int32_t eventNum = eventsBuf.eventNum; for (int32_t i = 0; i < eventNum; i++) { EventFilter(eventsBuf); - eventsBuf.readPos++; - if (eventsBuf.readPos == CIRCULAR_BUF_LEN) { + if (eventsBuf.readPos >= CIRCULAR_BUF_LEN) { eventsBuf.readPos = 0; } eventsBuf.eventNum--; @@ -313,5 +312,5 @@ int32_t SensorDataProcesser::DataThread(sptr dataProcesser, } } while (1); } -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS diff --git a/services/src/sensor_dump.cpp b/services/src/sensor_dump.cpp index 93950201242d7c6171f7f3fcbc5f6b867598422e..56e09e88f4c22f091cefa1aeaa84f404d6d9651c 100644 --- a/services/src/sensor_dump.cpp +++ b/services/src/sensor_dump.cpp @@ -49,7 +49,7 @@ enum { POSE_6DOF_DIMENSION = 15, DEFAULT_DIMENSION = 16, }; -} // namespace +} // namespace std::unordered_map SensorDump::sensorMap_ = { { SENSOR_TYPE_ID_ACCELEROMETER, "ACCELEROMETER" }, @@ -192,7 +192,7 @@ void SensorDump::DumpHelp(int32_t fd) dprintf(fd, " -l, --list: dump the sensor list\n"); dprintf(fd, " -c, --channel: dump the sensor data channel info\n"); dprintf(fd, " -o, --open: dump the opening sensors\n"); -#ifdef BUILD_VARIANT_ENG +#ifdef BUILD_VARIANT_ENG dprintf(fd, " -d, --data: dump the last 10 packages sensor data\n"); #endif // BUILD_VARIANT_ENG } @@ -253,7 +253,7 @@ bool SensorDump::DumpOpeningSensor(int32_t fd, const std::vector &sensor return true; } -#ifdef BUILD_VARIANT_ENG +#ifdef BUILD_VARIANT_ENG bool SensorDump::DumpSensorData(int32_t fd, ClientInfo &clientInfo) { dprintf(fd, "Last 10 packages sensor data:\n"); @@ -332,7 +332,7 @@ std::string SensorDump::GetDataBySensorId(int32_t sensorId, SensorData &sensorDa std::string str; int32_t dataLen = GetDataDimension(sensorId); if (sensorData.dataLen < sizeof(float)) { - SEN_HILOGE("SensorData dataLen less than float size."); + SEN_HILOGE("SensorData dataLen less than float size"); return str; } auto data = reinterpret_cast(sensorData.data); @@ -346,5 +346,5 @@ std::string SensorDump::GetDataBySensorId(int32_t sensorId, SensorData &sensorDa str.append("\n"); return str; } -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS diff --git a/services/src/sensor_service.cpp b/services/src/sensor_service.cpp index eef9a2f37e133c116e5b7e2fdeb20aa22a8193f0..8b2f78c3ca53d5a410d8db6433d92e6d25325309 100644 --- a/services/src/sensor_service.cpp +++ b/services/src/sensor_service.cpp @@ -27,6 +27,7 @@ #endif // MEMMGR_ENABLE #include "permission_util.h" +#include "print_sensor_data.h" #include "securec.h" #include "sensor.h" #include "sensor_dump.h" @@ -45,7 +46,7 @@ const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(g_sensorSer constexpr int32_t INVALID_PID = -1; constexpr int64_t MAX_EVENT_COUNT = 1000; std::atomic_bool g_isRegister = false; -} // namespace +} // namespace SensorService::SensorService() : SystemAbility(SENSOR_SERVICE_ABILITY_ID, true), state_(SensorServiceState::STATE_STOPPED) @@ -254,12 +255,21 @@ bool SensorService::CheckSensorId(int32_t sensorId) return true; } -ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +bool SensorService::CheckParameter(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) { - CALL_LOG_ENTER; if ((!CheckSensorId(sensorId)) || ((samplingPeriodNs != 0L) && ((maxReportDelayNs / samplingPeriodNs) > MAX_EVENT_COUNT))) { SEN_HILOGE("sensorId is invalid or maxReportDelayNs exceeded the maximum value"); + return false; + } + return true; +} + +ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +{ + CALL_LOG_ENTER; + if (!CheckParameter(sensorId, samplingPeriodNs, maxReportDelayNs)) { + SEN_HILOGE("sensorId, samplingPeriodNs or maxReportDelayNs is invalid"); return ERR_NO_INIT; } int32_t pid = GetCallingPid(); @@ -279,6 +289,7 @@ ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, if (isReportActiveInfo_) { ReportActiveInfo(sensorId, pid); } + PrintSensorData::GetInstance().ResetHdiCounter(sensorId); return ERR_OK; } auto ret = SaveSubscriber(sensorId, samplingPeriodNs, maxReportDelayNs); @@ -302,6 +313,7 @@ ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, if (isReportActiveInfo_) { ReportActiveInfo(sensorId, pid); } + PrintSensorData::GetInstance().ResetHdiCounter(sensorId); return ret; } @@ -607,5 +619,5 @@ void SensorService::PermStateChangeCb::PermStateChangeCallback(Security::AccessT server_->clientInfo_.ChangeSensorPerm(result.tokenID, result.permissionName, (result.permStateChangeType != 0)); } -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS diff --git a/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn b/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn index 2528534f1e256cecda7c72c1bfebe273a0dd2241..c379e57756a2e37056481579c152ca5b2bdb37b7 100644 --- a/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn +++ b/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn @@ -26,6 +26,7 @@ ohos_fuzztest("SensorAgentFuzzTest") { "$SUBSYSTEM_DIR/interfaces/inner_api", "$SUBSYSTEM_DIR/frameworks/native/include", "$SUBSYSTEM_DIR/test/fuzztest/interfaces/sensoragent_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", ] cflags = [ @@ -39,7 +40,13 @@ ohos_fuzztest("SensorAgentFuzzTest") { deps = [ "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native" ] - external_deps = [ "c_utils:utils" ] + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] } group("fuzztest") { diff --git a/test/fuzztest/interfaces/sensoragent_fuzzer/sensoragent_fuzzer.cpp b/test/fuzztest/interfaces/sensoragent_fuzzer/sensoragent_fuzzer.cpp index 60f564dc2e0b3f55cf267b1792d8ad8ee2f65268..f96be5b054e9bb04d26228f550cf06bdf7fdc647 100644 --- a/test/fuzztest/interfaces/sensoragent_fuzzer/sensoragent_fuzzer.cpp +++ b/test/fuzztest/interfaces/sensoragent_fuzzer/sensoragent_fuzzer.cpp @@ -15,11 +15,64 @@ #include "sensoragent_fuzzer.h" -#include "sensor_agent.h" -#include "sensor_agent_type.h" #include #include +#include "accesstoken_kit.h" +#include "token_setproc.h" +#include "nativetoken_kit.h" +#include "securec.h" + +#include "sensor_agent.h" +#include "sensor_agent_type.h" +#include "sensor_errors.h" + +namespace OHOS { +namespace Sensors { +using namespace OHOS::HiviewDFX; +using namespace OHOS::Security::AccessToken; +using OHOS::Security::AccessToken::AccessTokenID; +namespace { +constexpr int64_t g_samplingInterval = 200000000; +constexpr int64_t g_reportInterval = 200000000; +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + 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 SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + CHKPV(perms); + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "SensorAgentFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + void SensorDataCallbackImpl(SensorEvent *event) { if (event == nullptr) { @@ -43,39 +96,31 @@ bool CheckSensorTypeId(int32_t sensorTypeId) return false; } -bool SensorAgentFuzzTest(const uint8_t *data, size_t size) +void SensorAgentFuzzTest(const uint8_t *data, size_t size) { - intptr_t sensorTypeId = reinterpret_cast(data); + SetUpTestCase(); + size_t startPos = 0; + int32_t sensorTypeId = 0; + GetObject(sensorTypeId, data + startPos, size - startPos); bool validSensorId = CheckSensorTypeId(sensorTypeId); + if (!validSensorId) { + sensorTypeId = SENSOR_TYPE_ID_ACCELEROMETER; + } SensorUser user; user.callback = SensorDataCallbackImpl; - int32_t ret = SubscribeSensor(sensorTypeId, &user); - if (ret != 0) { - return validSensorId ? false : true; - } - ret = SetBatch(sensorTypeId, &user, 200000000, 0); - if (ret != 0) { - return validSensorId ? false : true; - } - ret = ActivateSensor(sensorTypeId, &user); - if (ret != 0) { - return validSensorId ? false : true; - } + SubscribeSensor(sensorTypeId, &user); + SetBatch(sensorTypeId, &user, g_samplingInterval, g_reportInterval); + ActivateSensor(sensorTypeId, &user); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); - ret = DeactivateSensor(sensorTypeId, &user); - if (ret != 0) { - return validSensorId ? false : true; - } - ret = UnsubscribeSensor(sensorTypeId, &user); - if (ret != 0) { - return validSensorId ? false : true; - } - return true; + DeactivateSensor(sensorTypeId, &user); + UnsubscribeSensor(sensorTypeId, &user); } +} // namespace Sensors +} // namespace OHOS extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { - SensorAgentFuzzTest(data, size); + OHOS::Sensors::SensorAgentFuzzTest(data, size); return 0; } diff --git a/test/fuzztest/services/BUILD.gn b/test/fuzztest/services/BUILD.gn index 6632a988c1f2eeb1ca081d39119aa316002fd17a..c15f56612c0cab4322e63f7acfcac2b2024bb3e0 100644 --- a/test/fuzztest/services/BUILD.gn +++ b/test/fuzztest/services/BUILD.gn @@ -31,6 +31,17 @@ group("fuzztest") { "sensordisablestub_fuzzer:fuzztest", "sensorenablestub_fuzzer:fuzztest", "sensoronremoterequest_fuzzer:fuzztest", + "service/createsocketchannel_fuzzer:fuzztest", + "service/destroysensorchannel_fuzzer:fuzztest", + "service/getactiveinfolist_fuzzer:fuzztest", + "service/onstart_fuzzer:fuzztest", + "service/processdeathobserver_fuzzer:fuzztest", + "service/registerclientdeathrecipient_fuzzer:fuzztest", + "service/registerpermcallback_fuzzer:fuzztest", + "service/reportactiveinfo_fuzzer:fuzztest", + "service/reportonchangedata_fuzzer:fuzztest", + "service/reportsensorsysevent_fuzzer:fuzztest", + "service/transferdatachannel_fuzzer:fuzztest", "suspendsensorsstub_fuzzer:fuzztest", ] } diff --git a/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn b/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..23265de468acf15037491aeef82e9450e4c5312d --- /dev/null +++ b/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2024 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") +import("./../../../../../sensor.gni") + +ohos_fuzztest("CreateSocketChannelFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/services/service/createsocketchannel_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/createsocketchannel_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "createsocketchannel_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":CreateSocketChannelFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/createsocketchannel_fuzzer/corpus/init b/test/fuzztest/services/service/createsocketchannel_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..7e96755ef6733c8a899d0d1b9b409ac5b0630860 --- /dev/null +++ b/test/fuzztest/services/service/createsocketchannel_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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/test/fuzztest/services/service/createsocketchannel_fuzzer/createsocketchannel_fuzzer.cpp b/test/fuzztest/services/service/createsocketchannel_fuzzer/createsocketchannel_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6215193eb2b06fbc212e1baadd217dd34f47bb11 --- /dev/null +++ b/test/fuzztest/services/service/createsocketchannel_fuzzer/createsocketchannel_fuzzer.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2024 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 "createsocketchannel_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +static sptr g_remote = new (std::nothrow) IPCObjectStub(); +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + 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 SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool CreateSocketChannelFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + if (g_remote == nullptr) { + return false; + } + int32_t clientFd = 0; + GetObject(clientFd, data, size); + g_service->CreateSocketChannel(g_remote, clientFd); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::CreateSocketChannelFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/createsocketchannel_fuzzer/createsocketchannel_fuzzer.h b/test/fuzztest/services/service/createsocketchannel_fuzzer/createsocketchannel_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..01c4999aaa585215ac2cf6479e4981f0f4ac24a7 --- /dev/null +++ b/test/fuzztest/services/service/createsocketchannel_fuzzer/createsocketchannel_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 CREATE_SOCKET_CHANNEL_FUZZER_H +#define CREATE_SOCKET_CHANNEL_FUZZER_H + +#define FUZZ_PROJECT_NAME "createsocketchannel_fuzzer" + +#endif // CREATE_SOCKET_CHANNEL_FUZZER_H + diff --git a/test/fuzztest/services/service/createsocketchannel_fuzzer/project.xml b/test/fuzztest/services/service/createsocketchannel_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..0188b886add2122343d39dde051488a97d90320f --- /dev/null +++ b/test/fuzztest/services/service/createsocketchannel_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/destroysensorchannel_fuzzer/BUILD.gn b/test/fuzztest/services/service/destroysensorchannel_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..daaadc84c726d3cef5d695b8dffa3834e2ecdb26 --- /dev/null +++ b/test/fuzztest/services/service/destroysensorchannel_fuzzer/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2024 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") +import("./../../../../../sensor.gni") + +ohos_fuzztest("DestroySensorChannelFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/services/service/destroysensorchannel_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/destroysensorchannel_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "destroysensorchannel_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":DestroySensorChannelFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/destroysensorchannel_fuzzer/corpus/init b/test/fuzztest/services/service/destroysensorchannel_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..7e96755ef6733c8a899d0d1b9b409ac5b0630860 --- /dev/null +++ b/test/fuzztest/services/service/destroysensorchannel_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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/test/fuzztest/services/service/destroysensorchannel_fuzzer/destroysensorchannel_fuzzer.cpp b/test/fuzztest/services/service/destroysensorchannel_fuzzer/destroysensorchannel_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ff4f80d638e63369bbfb7301c0d3ad73091173dc --- /dev/null +++ b/test/fuzztest/services/service/destroysensorchannel_fuzzer/destroysensorchannel_fuzzer.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2024 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 "destroysensorchannel_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +static sptr g_remote = new (std::nothrow) IPCObjectStub(); +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + 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 SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool DestroySensorChannelFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + if (g_remote == nullptr) { + return false; + } + g_service->DestroySensorChannel(g_remote); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::DestroySensorChannelFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/destroysensorchannel_fuzzer/destroysensorchannel_fuzzer.h b/test/fuzztest/services/service/destroysensorchannel_fuzzer/destroysensorchannel_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..16b108f997315d4eff33666b76d637a675bdf157 --- /dev/null +++ b/test/fuzztest/services/service/destroysensorchannel_fuzzer/destroysensorchannel_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 ON_START_FUZZER_H +#define ON_START_FUZZER_H + +#define FUZZ_PROJECT_NAME "onstart_fuzzer" + +#endif // ON_START_FUZZER_H + diff --git a/test/fuzztest/services/service/destroysensorchannel_fuzzer/project.xml b/test/fuzztest/services/service/destroysensorchannel_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..0188b886add2122343d39dde051488a97d90320f --- /dev/null +++ b/test/fuzztest/services/service/destroysensorchannel_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn b/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3757500426b82ecba5b2cf8850a008e2c5b998c3 --- /dev/null +++ b/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2024 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") +import("./../../../../../sensor.gni") + +ohos_fuzztest("GetActiveInfoListFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/services/service/getactiveinfolist_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/getactiveinfolist_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "getactiveinfolist_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":GetActiveInfoListFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/getactiveinfolist_fuzzer/corpus/init b/test/fuzztest/services/service/getactiveinfolist_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..7e96755ef6733c8a899d0d1b9b409ac5b0630860 --- /dev/null +++ b/test/fuzztest/services/service/getactiveinfolist_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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/test/fuzztest/services/service/getactiveinfolist_fuzzer/getactiveinfolist_fuzzer.cpp b/test/fuzztest/services/service/getactiveinfolist_fuzzer/getactiveinfolist_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e9092799077ab25ac35522fc409f6639337a27fa --- /dev/null +++ b/test/fuzztest/services/service/getactiveinfolist_fuzzer/getactiveinfolist_fuzzer.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2024 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 "getactiveinfolist_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + 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 SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool GetActiveInfoListFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + std::vector activeInfoList; + int32_t pid = 0; + GetObject(pid, data, size); + g_service->GetActiveInfoList(pid, activeInfoList); + g_service->SuspendSensors(pid); + g_service->ResumeSensors(pid); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::GetActiveInfoListFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/getactiveinfolist_fuzzer/getactiveinfolist_fuzzer.h b/test/fuzztest/services/service/getactiveinfolist_fuzzer/getactiveinfolist_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..8d57d1de1aff5a96637d03cea9a74f1c7ea542b2 --- /dev/null +++ b/test/fuzztest/services/service/getactiveinfolist_fuzzer/getactiveinfolist_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 GET_ACTIVE_INFO_LIST_FUZZER_H +#define GET_ACTIVE_INFO_LIST_FUZZER_H + +#define FUZZ_PROJECT_NAME "getactiveinfolist_fuzzer" + +#endif // GET_ACTIVE_INFO_LIST_FUZZER_H + diff --git a/test/fuzztest/services/service/getactiveinfolist_fuzzer/project.xml b/test/fuzztest/services/service/getactiveinfolist_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..0188b886add2122343d39dde051488a97d90320f --- /dev/null +++ b/test/fuzztest/services/service/getactiveinfolist_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/onstart_fuzzer/BUILD.gn b/test/fuzztest/services/service/onstart_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e23a38289cae02816399cf999804e76f3cfc957b --- /dev/null +++ b/test/fuzztest/services/service/onstart_fuzzer/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2024 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") +import("./../../../../../sensor.gni") + +ohos_fuzztest("OnStartFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/services/service/onstart_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/onstart_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "onstart_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":OnStartFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/onstart_fuzzer/corpus/init b/test/fuzztest/services/service/onstart_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..a5ac5cc450b3ce83b5a6c03e4233d9a1dba4ffbd --- /dev/null +++ b/test/fuzztest/services/service/onstart_fuzzer/corpus/init @@ -0,0 +1,14 @@ + # Copyright (c) 2024 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/test/fuzztest/services/service/onstart_fuzzer/onstart_fuzzer.cpp b/test/fuzztest/services/service/onstart_fuzzer/onstart_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3805005430572e6550ca0451cddab7e07e04aeb2 --- /dev/null +++ b/test/fuzztest/services/service/onstart_fuzzer/onstart_fuzzer.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2024 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 "onstart_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + 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 SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool OnStartFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + g_service->OnStart(); + g_service->OnStop(); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::OnStartFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/onstart_fuzzer/onstart_fuzzer.h b/test/fuzztest/services/service/onstart_fuzzer/onstart_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..16b108f997315d4eff33666b76d637a675bdf157 --- /dev/null +++ b/test/fuzztest/services/service/onstart_fuzzer/onstart_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 ON_START_FUZZER_H +#define ON_START_FUZZER_H + +#define FUZZ_PROJECT_NAME "onstart_fuzzer" + +#endif // ON_START_FUZZER_H + diff --git a/test/fuzztest/services/service/onstart_fuzzer/project.xml b/test/fuzztest/services/service/onstart_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..0188b886add2122343d39dde051488a97d90320f --- /dev/null +++ b/test/fuzztest/services/service/onstart_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/processdeathobserver_fuzzer/BUILD.gn b/test/fuzztest/services/service/processdeathobserver_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..14dee0ea37943c595912ea4e6e76f2fd8c740255 --- /dev/null +++ b/test/fuzztest/services/service/processdeathobserver_fuzzer/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2024 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") +import("./../../../../../sensor.gni") + +ohos_fuzztest("ProcessDeathObserverFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/services/service/processdeathobserver_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/processdeathobserver_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "processdeathobserver_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":ProcessDeathObserverFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/processdeathobserver_fuzzer/corpus/init b/test/fuzztest/services/service/processdeathobserver_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..7e96755ef6733c8a899d0d1b9b409ac5b0630860 --- /dev/null +++ b/test/fuzztest/services/service/processdeathobserver_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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/test/fuzztest/services/service/processdeathobserver_fuzzer/processdeathobserver_fuzzer.cpp b/test/fuzztest/services/service/processdeathobserver_fuzzer/processdeathobserver_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2d15b5fb911934a4bae6a99ef7ee7e6a79495162 --- /dev/null +++ b/test/fuzztest/services/service/processdeathobserver_fuzzer/processdeathobserver_fuzzer.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2024 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 "processdeathobserver_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +static sptr g_remote = new (std::nothrow) IPCObjectStub(); +} // namespace + +void SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool ProcessDeathObserverFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + if (g_remote == nullptr) { + return false; + } + g_service->ProcessDeathObserver(g_remote); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::ProcessDeathObserverFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/processdeathobserver_fuzzer/processdeathobserver_fuzzer.h b/test/fuzztest/services/service/processdeathobserver_fuzzer/processdeathobserver_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..4e91e0d046d4c6dcdf3b847ad2679ca4ee527cba --- /dev/null +++ b/test/fuzztest/services/service/processdeathobserver_fuzzer/processdeathobserver_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 PROCESS_DEATH_OBSERVER_FUZZER_H +#define PROCESS_DEATH_OBSERVER_FUZZER_H + +#define FUZZ_PROJECT_NAME "processdeathobserver_fuzzer" + +#endif // PROCESS_DEATH_OBSERVER_FUZZER_H + diff --git a/test/fuzztest/services/service/processdeathobserver_fuzzer/project.xml b/test/fuzztest/services/service/processdeathobserver_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..0188b886add2122343d39dde051488a97d90320f --- /dev/null +++ b/test/fuzztest/services/service/processdeathobserver_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..944b4e941545826ca4a17431ff61e551727067d7 --- /dev/null +++ b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2024 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") +import("./../../../../../sensor.gni") + +ohos_fuzztest("RegisterClientDeathRecipientFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "registerclientdeathrecipient_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":RegisterClientDeathRecipientFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/corpus/init b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..7e96755ef6733c8a899d0d1b9b409ac5b0630860 --- /dev/null +++ b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/project.xml b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..0188b886add2122343d39dde051488a97d90320f --- /dev/null +++ b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/registerclientdeathrecipient_fuzzer.cpp b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/registerclientdeathrecipient_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d563ebad7e4aaa2e8f75d750f6b0068674f3765 --- /dev/null +++ b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/registerclientdeathrecipient_fuzzer.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2024 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 "registerclientdeathrecipient_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +static sptr g_remote = new (std::nothrow) IPCObjectStub(); +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + 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 SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool RegisterClientDeathRecipientFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + if (g_remote == nullptr) { + return false; + } + int32_t pid = 0; + GetObject(pid, data, size); + g_service->RegisterClientDeathRecipient(g_remote, pid); + g_service->UnregisterClientDeathRecipient(g_remote); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::RegisterClientDeathRecipientFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/registerclientdeathrecipient_fuzzer.h b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/registerclientdeathrecipient_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..53dababcf87a14c88c4ee191c8ef747c6940dfee --- /dev/null +++ b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/registerclientdeathrecipient_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 REGISTER_CLIENT_DEATH_RECIPIENT_FUZZER_H +#define REGISTER_CLIENT_DEATH_RECIPIENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "registerclientdeathrecipient_fuzzer" + +#endif // REGISTER_CLIENT_DEATH_RECIPIENT_FUZZER_H + diff --git a/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn b/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..bb8e8092a7712c3a942402b185bb8dcc0a8255d0 --- /dev/null +++ b/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2024 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") +import("./../../../../../sensor.gni") + +ohos_fuzztest("RegisterPermCallbackFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/services/service/registerpermcallback_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/registerpermcallback_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "registerpermcallback_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":RegisterPermCallbackFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/registerpermcallback_fuzzer/corpus/init b/test/fuzztest/services/service/registerpermcallback_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..7e96755ef6733c8a899d0d1b9b409ac5b0630860 --- /dev/null +++ b/test/fuzztest/services/service/registerpermcallback_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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/test/fuzztest/services/service/registerpermcallback_fuzzer/project.xml b/test/fuzztest/services/service/registerpermcallback_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..0188b886add2122343d39dde051488a97d90320f --- /dev/null +++ b/test/fuzztest/services/service/registerpermcallback_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/registerpermcallback_fuzzer/registerpermcallback_fuzzer.cpp b/test/fuzztest/services/service/registerpermcallback_fuzzer/registerpermcallback_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea2bae125233aebd8dd913d60ad6695fdd50aaea --- /dev/null +++ b/test/fuzztest/services/service/registerpermcallback_fuzzer/registerpermcallback_fuzzer.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2024 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 "registerpermcallback_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + 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 SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool RegisterPermCallbackFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + int32_t sensorId = 0; + GetObject(sensorId, data, size); + g_service->RegisterPermCallback(sensorId); + g_service->UnregisterPermCallback(); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::RegisterPermCallbackFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/registerpermcallback_fuzzer/registerpermcallback_fuzzer.h b/test/fuzztest/services/service/registerpermcallback_fuzzer/registerpermcallback_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..a89a478edf29dcf8160a72012266e2b30deeda29 --- /dev/null +++ b/test/fuzztest/services/service/registerpermcallback_fuzzer/registerpermcallback_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 REGISTER_PERM_CALLBACK_FUZZER_H +#define REGISTER_PERM_CALLBACK_FUZZER_H + +#define FUZZ_PROJECT_NAME "registerpermcallback_fuzzer" + +#endif // REGISTER_PERM_CALLBACK_FUZZER_H + diff --git a/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn b/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..360b62d6029ef39e960b5a66d998806f14c8e1d6 --- /dev/null +++ b/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2024 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") +import("./../../../../../sensor.gni") + +ohos_fuzztest("ReportActiveInfoFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/services/service/reportactiveinfo_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/reportactiveinfo_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "reportactiveinfo_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":ReportActiveInfoFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/reportactiveinfo_fuzzer/corpus/init b/test/fuzztest/services/service/reportactiveinfo_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..7e96755ef6733c8a899d0d1b9b409ac5b0630860 --- /dev/null +++ b/test/fuzztest/services/service/reportactiveinfo_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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/test/fuzztest/services/service/reportactiveinfo_fuzzer/project.xml b/test/fuzztest/services/service/reportactiveinfo_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..0188b886add2122343d39dde051488a97d90320f --- /dev/null +++ b/test/fuzztest/services/service/reportactiveinfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/reportactiveinfo_fuzzer/reportactiveinfo_fuzzer.cpp b/test/fuzztest/services/service/reportactiveinfo_fuzzer/reportactiveinfo_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..298e6adea17685476eb74b34b54086a1d9269c12 --- /dev/null +++ b/test/fuzztest/services/service/reportactiveinfo_fuzzer/reportactiveinfo_fuzzer.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2024 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 "reportactiveinfo_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + 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 SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool ReportActiveInfoFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + size_t startPos = 0; + int32_t sensorId = 0; + startPos += GetObject(sensorId, data + startPos, size - startPos); + int32_t pid = 0; + startPos += GetObject(pid, data + startPos, size - startPos); + g_service->ReportActiveInfo(sensorId, pid); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::ReportActiveInfoFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/reportactiveinfo_fuzzer/reportactiveinfo_fuzzer.h b/test/fuzztest/services/service/reportactiveinfo_fuzzer/reportactiveinfo_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..37fc8159681af3625f7a5323535b74fa1161b72f --- /dev/null +++ b/test/fuzztest/services/service/reportactiveinfo_fuzzer/reportactiveinfo_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 REPOR_ACTIVE_INFO_FUZZER_H +#define REPOR_ACTIVE_INFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "reportactiveinfo_fuzzer" + +#endif // REPOR_ACTIVE_INFO_FUZZER_H + diff --git a/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn b/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4a6d8f5a300d956defd096272449cb8ef1c6a9a2 --- /dev/null +++ b/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2024 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") +import("./../../../../../sensor.gni") + +ohos_fuzztest("ReportOnChangeDataFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/services/service/reportonchangedata_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/reportonchangedata_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "reportonchangedata_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":ReportOnChangeDataFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/reportonchangedata_fuzzer/corpus/init b/test/fuzztest/services/service/reportonchangedata_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..7e96755ef6733c8a899d0d1b9b409ac5b0630860 --- /dev/null +++ b/test/fuzztest/services/service/reportonchangedata_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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/test/fuzztest/services/service/reportonchangedata_fuzzer/project.xml b/test/fuzztest/services/service/reportonchangedata_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..0188b886add2122343d39dde051488a97d90320f --- /dev/null +++ b/test/fuzztest/services/service/reportonchangedata_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/reportonchangedata_fuzzer/reportonchangedata_fuzzer.cpp b/test/fuzztest/services/service/reportonchangedata_fuzzer/reportonchangedata_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..67545d06e862addc2fb6e5097a36a196485f132f --- /dev/null +++ b/test/fuzztest/services/service/reportonchangedata_fuzzer/reportonchangedata_fuzzer.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2024 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 "reportonchangedata_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + 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 SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool ReportOnChangeDataFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + g_service->OnStart(); + int32_t sensorId = 0; + GetObject(sensorId, data, size); + g_service->ReportOnChangeData(sensorId); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::ReportOnChangeDataFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/reportonchangedata_fuzzer/reportonchangedata_fuzzer.h b/test/fuzztest/services/service/reportonchangedata_fuzzer/reportonchangedata_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..838e3c272aa8cf5f39356037834925adb5469609 --- /dev/null +++ b/test/fuzztest/services/service/reportonchangedata_fuzzer/reportonchangedata_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 REPORT_ON_CHANGE_DATA_FUZZER_H +#define REPORT_ON_CHANGE_DATA_FUZZER_H + +#define FUZZ_PROJECT_NAME "reportonchangedata_fuzzer" + +#endif // REPORT_ON_CHANGE_DATA_FUZZER_H + diff --git a/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6b4c3849c0a3a9fc1fc66af0fd5a89f97565727f --- /dev/null +++ b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2024 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") +import("./../../../../../sensor.gni") + +ohos_fuzztest("ReportSensorSysEventFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/services/service/reportsensorsysevent_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/reportsensorsysevent_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "reportsensorsysevent_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":ReportSensorSysEventFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/reportsensorsysevent_fuzzer/corpus/init b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..7e96755ef6733c8a899d0d1b9b409ac5b0630860 --- /dev/null +++ b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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/test/fuzztest/services/service/reportsensorsysevent_fuzzer/project.xml b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..0188b886add2122343d39dde051488a97d90320f --- /dev/null +++ b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/reportsensorsysevent_fuzzer/reportsensorsysevent_fuzzer.cpp b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/reportsensorsysevent_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19faf7c0ffbf5ce4fd00b3e696cc82d2c4fdd58e --- /dev/null +++ b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/reportsensorsysevent_fuzzer.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2024 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 "reportsensorsysevent_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + 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 SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool ReportSensorSysEventFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + size_t startPos = 0; + int32_t sensorId = 0; + startPos += GetObject(sensorId, data + startPos, size - startPos); + bool enable = false; + startPos += GetObject(enable, data + startPos, size - startPos); + int32_t pid = 0; + startPos += GetObject(pid, data + startPos, size - startPos); + g_service->ReportSensorSysEvent(sensorId, enable, pid); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::ReportSensorSysEventFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/reportsensorsysevent_fuzzer/reportsensorsysevent_fuzzer.h b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/reportsensorsysevent_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..ea23ed7dfc0f8add812e7d0684edcb7f374e4962 --- /dev/null +++ b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/reportsensorsysevent_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 REPORT_SENSOR_SYS_EVENT_FUZZER_H +#define REPORT_SENSOR_SYS_EVENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "reportsensorsysevent_fuzzer" + +#endif // REPORT_SENSOR_SYS_EVENT_FUZZER_H + diff --git a/test/fuzztest/services/service/transferdatachannel_fuzzer/BUILD.gn b/test/fuzztest/services/service/transferdatachannel_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..00036738d94b737e23ae8d91d642bb4abd0088b7 --- /dev/null +++ b/test/fuzztest/services/service/transferdatachannel_fuzzer/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2024 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") +import("./../../../../../sensor.gni") + +ohos_fuzztest("TransferDataChannelFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/services/service/transferdatachannel_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/transferdatachannel_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "transferdatachannel_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":TransferDataChannelFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/transferdatachannel_fuzzer/corpus/init b/test/fuzztest/services/service/transferdatachannel_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..7e96755ef6733c8a899d0d1b9b409ac5b0630860 --- /dev/null +++ b/test/fuzztest/services/service/transferdatachannel_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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/test/fuzztest/services/service/transferdatachannel_fuzzer/project.xml b/test/fuzztest/services/service/transferdatachannel_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..0188b886add2122343d39dde051488a97d90320f --- /dev/null +++ b/test/fuzztest/services/service/transferdatachannel_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/transferdatachannel_fuzzer/transferdatachannel_fuzzer.cpp b/test/fuzztest/services/service/transferdatachannel_fuzzer/transferdatachannel_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f7c6ad514216bed92e6e846fb0d5b30229ee5b9 --- /dev/null +++ b/test/fuzztest/services/service/transferdatachannel_fuzzer/transferdatachannel_fuzzer.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2024 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 "transferdatachannel_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +static sptr g_remote = new (std::nothrow) IPCObjectStub(); +static sptr g_dataChannel = new (std::nothrow) SensorBasicDataChannel(); +} // namespace + +void SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool TransferDataChannelFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + if (g_remote == nullptr || g_dataChannel == nullptr) { + return false; + } + g_service->TransferDataChannel(g_dataChannel, g_remote); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::TransferDataChannelFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/transferdatachannel_fuzzer/transferdatachannel_fuzzer.h b/test/fuzztest/services/service/transferdatachannel_fuzzer/transferdatachannel_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..e1a8af074a03585996db86e401854e293d08e8a3 --- /dev/null +++ b/test/fuzztest/services/service/transferdatachannel_fuzzer/transferdatachannel_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 TRANFER_DATA_CHANNEL_FUZZER_H +#define TRANFER_DATA_CHANNEL_FUZZER_H + +#define FUZZ_PROJECT_NAME "transferdatachannel_fuzzer" + +#endif // TRANFER_DATA_CHANNEL_FUZZER_H + diff --git a/test/unittest/coverage/BUILD.gn b/test/unittest/coverage/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3245e5aaae92302f6f9a94e66f79b5775cb2c96d --- /dev/null +++ b/test/unittest/coverage/BUILD.gn @@ -0,0 +1,79 @@ +# Copyright (c) 2024 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/test.gni") +import("./../../../sensor.gni") + +ohos_unittest("SensorBasicDataChannelTest") { + module_out_path = "sensor/coverage" + + sources = [ + "$SUBSYSTEM_DIR/test/unittest/coverage/sensor_basic_data_channel_test.cpp", + ] + + include_dirs = [ + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/interfaces/kits/c", + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + ] + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:libsensor_client", + "$SUBSYSTEM_DIR/frameworks/native:ohsensor", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + ] + + external_deps = [ + "c_utils:utils", + "googletest:gmock", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_single", + ] +} + +ohos_unittest("ReportDataCallbackTest") { + module_out_path = "sensor/coverage" + + sources = + [ "$SUBSYSTEM_DIR/test/unittest/coverage/report_data_callback_test.cpp" ] + + include_dirs = [ + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/interfaces/kits/c", + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + ] + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:libsensor_client", + "$SUBSYSTEM_DIR/frameworks/native:ohsensor", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + ] + + external_deps = [ + "c_utils:utils", + "googletest:gmock", + "googletest:gtest_main", + "hilog:libhilog", + ] +} + +group("unittest") { + testonly = true + deps = [ + ":ReportDataCallbackTest", + ":SensorBasicDataChannelTest", + ] +} diff --git a/test/unittest/coverage/report_data_callback_test.cpp b/test/unittest/coverage/report_data_callback_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..280e643f1f6ade01732724a63f974127a80d717b --- /dev/null +++ b/test/unittest/coverage/report_data_callback_test.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2024 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 "report_data_callback.h" +#include "sensor_errors.h" + +#undef LOG_TAG +#define LOG_TAG "ReportDataCallbackTest" + +namespace OHOS { +namespace Sensors { +using namespace testing::ext; + +namespace { + SensorData* g_sensorData = new (std::nothrow) SensorData[CIRCULAR_BUF_LEN]; +} // namespace + +class SensorBasicDataChannelTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void SensorBasicDataChannelTest::SetUpTestCase() {} + +void SensorBasicDataChannelTest::TearDownTestCase() +{ + if (g_sensorData != nullptr) { + delete[] g_sensorData; + g_sensorData = nullptr; + } +} + +void SensorBasicDataChannelTest::SetUp() {} + +void SensorBasicDataChannelTest::TearDown() {} + +HWTEST_F(SensorBasicDataChannelTest, ReportDataCallbackTest_001, TestSize.Level1) +{ + SEN_HILOGI("ReportDataCallbackTest_001 in"); + + ReportDataCallback reportDataCallback = ReportDataCallback(); + ReportDataCallback *cb = nullptr; + int32_t ret = reportDataCallback.ReportEventCallback(g_sensorData, cb); + ASSERT_EQ(ret, ERROR); + + sptr callback = new (std::nothrow) ReportDataCallback(); + if (callback->eventsBuf_.circularBuf != nullptr) { + delete[] callback->eventsBuf_.circularBuf; + callback->eventsBuf_.circularBuf = nullptr; + } + callback->eventsBuf_.circularBuf = nullptr; + ret = reportDataCallback.ReportEventCallback(g_sensorData, callback); + ASSERT_EQ(ret, ERROR); +} + +HWTEST_F(SensorBasicDataChannelTest, ReportDataCallbackTest_002, TestSize.Level1) +{ + SEN_HILOGI("ReportDataCallbackTest_002 in"); + + ReportDataCallback reportDataCallback = ReportDataCallback(); + sptr callback = new (std::nothrow) ReportDataCallback(); + callback->eventsBuf_.eventNum = CIRCULAR_BUF_LEN + 1; + callback->eventsBuf_.writePosition = 1; + int32_t ret = reportDataCallback.ReportEventCallback(g_sensorData, callback); + ASSERT_EQ(ret, ERROR); + + callback->eventsBuf_.eventNum = 1; + callback->eventsBuf_.writePosition = CIRCULAR_BUF_LEN + 1; + ret = reportDataCallback.ReportEventCallback(g_sensorData, callback); + ASSERT_EQ(ret, ERROR); +} + +HWTEST_F(SensorBasicDataChannelTest, ReportDataCallbackTest_003, TestSize.Level1) +{ + SEN_HILOGI("ReportDataCallbackTest_003 in"); + ReportDataCallback reportDataCallback = ReportDataCallback(); + sptr callback = new (std::nothrow) ReportDataCallback(); + callback->eventsBuf_.eventNum = CIRCULAR_BUF_LEN; + callback->eventsBuf_.writePosition = CIRCULAR_BUF_LEN; + int32_t ret = reportDataCallback.ReportEventCallback(g_sensorData, callback); + ASSERT_EQ(ret, ERR_OK); +} + +HWTEST_F(SensorBasicDataChannelTest, ReportDataCallbackTest_004, TestSize.Level1) +{ + SEN_HILOGI("ReportDataCallbackTest_004 in"); + ReportDataCallback reportDataCallback = ReportDataCallback(); + sptr callback = new (std::nothrow) ReportDataCallback(); + callback->eventsBuf_.eventNum = CIRCULAR_BUF_LEN; + callback->eventsBuf_.writePosition = 1; + int32_t ret = reportDataCallback.ReportEventCallback(g_sensorData, callback); + ASSERT_EQ(ret, ERR_OK); +} + +HWTEST_F(SensorBasicDataChannelTest, ReportDataCallbackTest_005, TestSize.Level1) +{ + SEN_HILOGI("ReportDataCallbackTest_005 in"); + ReportDataCallback reportDataCallback = ReportDataCallback(); + sptr callback = new (std::nothrow) ReportDataCallback(); + callback->eventsBuf_.eventNum = CIRCULAR_BUF_LEN; + callback->eventsBuf_.writePosition = CIRCULAR_BUF_LEN - 1; + int32_t ret = reportDataCallback.ReportEventCallback(g_sensorData, callback); + ASSERT_EQ(ret, ERR_OK); +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/coverage/sensor_basic_data_channel_test.cpp b/test/unittest/coverage/sensor_basic_data_channel_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e4016aa76f0da165f1ba30310f4b61c3ab9c3c33 --- /dev/null +++ b/test/unittest/coverage/sensor_basic_data_channel_test.cpp @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "message_parcel.h" + +#include "sensor_errors.h" +#include "sensor_basic_data_channel.h" + +#undef LOG_TAG +#define LOG_TAG "SensorBasicDataChannelTest" + +namespace OHOS { +namespace Sensors { +using namespace testing::ext; +using namespace OHOS::HiviewDFX; + +namespace { +constexpr int32_t INVALID_FD = 2; +} // namespace + +class SensorBasicDataChannelTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void SensorBasicDataChannelTest::SetUpTestCase() {} + +void SensorBasicDataChannelTest::TearDownTestCase() {} + +void SensorBasicDataChannelTest::SetUp() {} + +void SensorBasicDataChannelTest::TearDown() {} + +HWTEST_F(SensorBasicDataChannelTest, SensorBasicDataChannelTest_001, TestSize.Level1) +{ + SEN_HILOGI("SensorBasicDataChannelTest_001 in"); + + SensorBasicDataChannel sensorChannel = SensorBasicDataChannel(); + MessageParcel data; + int32_t ret = sensorChannel.CreateSensorBasicChannel(); + ASSERT_EQ(ret, ERR_OK); + ret = sensorChannel.CreateSensorBasicChannel(data); + ASSERT_EQ(ret, ERR_OK); + + ret = sensorChannel.SendToBinder(data); + ASSERT_EQ(ret, ERR_OK); + + char buff[128] = {}; + ret = sensorChannel.SendData(static_cast(buff), sizeof(buff)); + ASSERT_EQ(ret, ERR_OK); + + ret = sensorChannel.ReceiveData(static_cast(buff), sizeof(buff)); + ASSERT_NE(ret, SENSOR_CHANNEL_RECEIVE_ADDR_ERR); + + sensorChannel.DestroySensorBasicChannel(); +} + +HWTEST_F(SensorBasicDataChannelTest, CreateSensorBasicChannel_001, TestSize.Level1) +{ + SEN_HILOGI("CreateSensorBasicChannel_001 in"); + + SensorBasicDataChannel sensorChannel = SensorBasicDataChannel(); + MessageParcel data; + data.WriteFileDescriptor(INVALID_FD); + int32_t ret = sensorChannel.CreateSensorBasicChannel(data); + ASSERT_EQ(ret, ERR_OK); + + ret = sensorChannel.CreateSensorBasicChannel(data); + ASSERT_EQ(ret, ERR_OK); +} + +HWTEST_F(SensorBasicDataChannelTest, CreateSensorBasicChannel_002, TestSize.Level1) +{ + SEN_HILOGI("CreateSensorBasicChannel_002 in"); + SensorBasicDataChannel sensorChannel = SensorBasicDataChannel(); + MessageParcel data; + int32_t ret = sensorChannel.CreateSensorBasicChannel(data); + ASSERT_EQ(ret, SENSOR_CHANNEL_READ_DESCRIPTOR_ERR); +} + +HWTEST_F(SensorBasicDataChannelTest, SendToBinder_001, TestSize.Level1) +{ + SEN_HILOGI("SendToBinder_001 in"); + SensorBasicDataChannel sensorChannel = SensorBasicDataChannel(); + MessageParcel data; + int32_t ret = sensorChannel.SendToBinder(data); + ASSERT_EQ(ret, SENSOR_CHANNEL_SENDFD_ERR); +} + +HWTEST_F(SensorBasicDataChannelTest, SendData_001, TestSize.Level1) +{ + SEN_HILOGI("SendData_001 in"); + SensorBasicDataChannel sensorChannel = SensorBasicDataChannel(); + char buff[128] = {}; + int32_t ret = sensorChannel.SendData(static_cast(buff), sizeof(buff)); + ASSERT_EQ(ret, SENSOR_CHANNEL_SEND_ADDR_ERR); +} + +HWTEST_F(SensorBasicDataChannelTest, SendData_002, TestSize.Level1) +{ + SEN_HILOGI("SendData_002 in"); + SensorBasicDataChannel sensorChannel = SensorBasicDataChannel(); + MessageParcel data; + data.WriteFileDescriptor(INVALID_FD); + int32_t ret = sensorChannel.CreateSensorBasicChannel(data); + ASSERT_EQ(ret, ERR_OK); + char buff[128] = {}; + ret = sensorChannel.SendData(static_cast(buff), sizeof(buff)); + ASSERT_EQ(ret, SENSOR_CHANNEL_SEND_DATA_ERR); +} + +HWTEST_F(SensorBasicDataChannelTest, ReceiveData_001, TestSize.Level1) +{ + SEN_HILOGI("ReceiveData_001 in"); + SensorBasicDataChannel sensorChannel = SensorBasicDataChannel(); + char buff[128] = {}; + int32_t ret = sensorChannel.ReceiveData(static_cast(buff), sizeof(buff)); + ASSERT_EQ(ret, SENSOR_CHANNEL_RECEIVE_ADDR_ERR); + + sensorChannel.CreateSensorBasicChannel(); + char *buff1 = nullptr; + ret = sensorChannel.ReceiveData(static_cast(buff1), sizeof(buff1)); + ASSERT_EQ(ret, SENSOR_CHANNEL_RECEIVE_ADDR_ERR); + + sensorChannel.DestroySensorBasicChannel(); +} + +} // namespace Sensors +} // namespace OHOS diff --git a/test/unittest/interfaces/inner_api/drop_detection_test.cpp b/test/unittest/interfaces/inner_api/drop_detection_test.cpp index cfae3d7a5821e286c7195b00397509f5859d0d8d..a1bd4f3dff75e47887e01219c4d8e927ec950769 100644 --- a/test/unittest/interfaces/inner_api/drop_detection_test.cpp +++ b/test/unittest/interfaces/inner_api/drop_detection_test.cpp @@ -83,10 +83,6 @@ void DropDetectionDataCallbackImpl(SensorEvent *event) return; } DropDetectionData *dropDetectionData = reinterpret_cast(event[0].data); - if (dropDetectionData == nullptr) { - SEN_HILOGE("dropDetectionData is nullptr"); - return; - } SEN_HILOGD("sensorId:%{public}d, version:%{public}d, dataLen:%{public}u, status:%{public}f", event[0].sensorTypeId, event[0].version, event[0].dataLen, dropDetectionData->status); } @@ -106,10 +102,6 @@ void DropDetectionDataCallbackImpl2(SensorEvent *event) return; } DropDetectionData *dropDetectionData = reinterpret_cast(event[0].data); - if (dropDetectionData == nullptr) { - SEN_HILOGE("dropDetectionData is nullptr"); - return; - } SEN_HILOGD("sensorId:%{public}d, version:%{public}d, dataLen:%{public}u, status:%{public}f", event[0].sensorTypeId, event[0].version, event[0].dataLen, dropDetectionData->status); } diff --git a/test/unittest/interfaces/inner_api/sensor_algorithm_test.cpp b/test/unittest/interfaces/inner_api/sensor_algorithm_test.cpp index 9bac6570a82507b54e19c46f6beac0acd4e13177..7c42af4ba4ac64cc3375d0b5eff550ead8377788 100644 --- a/test/unittest/interfaces/inner_api/sensor_algorithm_test.cpp +++ b/test/unittest/interfaces/inner_api/sensor_algorithm_test.cpp @@ -31,6 +31,7 @@ namespace { constexpr int32_t QUATERNION_LENGTH = 4; constexpr int32_t ROTATION_VECTOR_LENGTH = 3; constexpr int32_t THREE_DIMENSIONAL_MATRIX_LENGTH = 9; +constexpr int32_t FOUR_DIMENSIONAL_MATRIX_LENGTH = 16; constexpr float EPS = 0.01; } // namespace @@ -87,6 +88,16 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_003, TestSize.Level1) HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_004, TestSize.Level1) { SEN_HILOGI("SensorAlgorithmTest_004 in"); + std::vector rotationVector = {0.52, -0.336, -0.251, 0.1}; + std::vector quaternion(QUATERNION_LENGTH); + int32_t ret = sensorAlgorithm.CreateQuaternion(rotationVector, quaternion); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + + +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_005, TestSize.Level1) +{ + SEN_HILOGI("SensorAlgorithmTest_005 in"); std::vector inRotationMatrix = {1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5}; std::vector outRotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); int32_t ret = sensorAlgorithm.TransformCoordinateSystem(inRotationMatrix, 1, 2, outRotationMatrix); @@ -99,34 +110,74 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_004, TestSize.Level1) } } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_005, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_006, TestSize.Level1) { - SEN_HILOGI("SensorAlgorithmTest_005 in"); + SEN_HILOGI("SensorAlgorithmTest_006 in"); std::vector inRotationMatrix(3); std::vector outRotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); int32_t ret = sensorAlgorithm.TransformCoordinateSystem(inRotationMatrix, 1, 2, outRotationMatrix); ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_006, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_007, TestSize.Level1) { - SEN_HILOGI("SensorAlgorithmTest_006 in"); + SEN_HILOGI("SensorAlgorithmTest_007 in"); std::vector inRotationMatrix = {1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5}; std::vector outRotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); int32_t ret = sensorAlgorithm.TransformCoordinateSystem(inRotationMatrix, 1, -1, outRotationMatrix); ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_007, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_008, TestSize.Level1) { - SEN_HILOGI("SensorAlgorithmTest_007 in"); + SEN_HILOGI("SensorAlgorithmTest_008 in"); std::vector inRotationMatrix = {1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5}; std::vector outRotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); int32_t ret = sensorAlgorithm.TransformCoordinateSystem(inRotationMatrix, -1, 1, outRotationMatrix); ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_008, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_009, TestSize.Level1) +{ + SEN_HILOGD("SensorAlgorithmTest_009 in"); + std::vector inRotationMatrix = {1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5}; + std::vector outRotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); + int32_t ret = sensorAlgorithm.TransformCoordinateSystem(inRotationMatrix, 0, 2, outRotationMatrix); + ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); + ret = sensorAlgorithm.TransformCoordinateSystem(inRotationMatrix, 3, 3, outRotationMatrix); + ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); +} + +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_010, TestSize.Level1) +{ + SEN_HILOGD("SensorAlgorithmTest_010 in"); + std::vector inRotationMatrix = {1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5}; + std::vector outRotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); + int32_t ret = sensorAlgorithm.TransformCoordinateSystem(inRotationMatrix, 1, 3, outRotationMatrix); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_011, TestSize.Level1) +{ + SEN_HILOGD("SensorAlgorithmTest_011 in"); + std::vector inRotationMatrix = {1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5}; + int32_t ret = sensorAlgorithm.TransformCoordinateSystem(inRotationMatrix, 0, 2, inRotationMatrix); + ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); + ret = sensorAlgorithm.TransformCoordinateSystem(inRotationMatrix, 0, 2, inRotationMatrix); + ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); +} + +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_012, TestSize.Level1) +{ + SEN_HILOGD("SensorAlgorithmTest_012"); + std::vector inRotationMatrix = {1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, + 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5}; + std::vector outRotationMatrix(FOUR_DIMENSIONAL_MATRIX_LENGTH); + int32_t ret = sensorAlgorithm.TransformCoordinateSystem(inRotationMatrix, 1, 2, outRotationMatrix); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_013, TestSize.Level1) { float altitude = -1.0; int32_t ret = sensorAlgorithm.GetAltitude(5.0, 0.0, &altitude); @@ -134,13 +185,13 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_008, TestSize.Level1) ASSERT_EQ(altitude, 44330.0); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_009, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_014, TestSize.Level1) { int32_t ret = sensorAlgorithm.GetAltitude(5.0, 0.0, nullptr); ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_010, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_015, TestSize.Level1) { float geomagneticDip = -1.0; std::vector inclinationMatrix = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}; @@ -149,14 +200,14 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_010, TestSize.Level1) ASSERT_EQ(geomagneticDip, 0.8760581016540527); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_011, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_016, TestSize.Level1) { std::vector inclinationMatrix = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}; int32_t ret = sensorAlgorithm.GetGeomagneticDip(inclinationMatrix, nullptr); ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_012, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_017, TestSize.Level1) { std::vector inclinationMatrix(3); float geomagneticDip = -1.0; @@ -164,7 +215,17 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_012, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_013, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_018, TestSize.Level1) +{ + SEN_HILOGI("SensorAlgorithmTest_017 in"); + float geomagneticDip = -1.0; + std::vector inclinationMatrix = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, + 9.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}; + int32_t ret = sensorAlgorithm.GetGeomagneticDip(inclinationMatrix, &geomagneticDip); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_019, TestSize.Level1) { std::vector currotationMatrix = {1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38}; @@ -180,7 +241,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_013, TestSize.Level1) } } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_014, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_020, TestSize.Level1) { std::vector currotationMatrix(3); std::vector preRotationMatrix = {1.17549e-38, 1.17549e-38, 1.17549e-38, @@ -190,7 +251,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_014, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_015, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_021, TestSize.Level1) { std::vector currotationMatrix = {1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38}; @@ -200,7 +261,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_015, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_016, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_022, TestSize.Level1) { std::vector currotationMatrix = {1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38, 1.17549e-38}; @@ -211,7 +272,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_016, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_017, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_023, TestSize.Level1) { std::vector rotationMatrix = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}; std::vector rotationAngle(ROTATION_VECTOR_LENGTH); @@ -224,7 +285,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_017, TestSize.Level1) } } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_018, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_024, TestSize.Level1) { std::vector rotationMatrix(5); std::vector rotationAngle(ROTATION_VECTOR_LENGTH); @@ -232,7 +293,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_018, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_019, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_025, TestSize.Level1) { std::vector rotationMatrix = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}; std::vector rotationAngle(ROTATION_VECTOR_LENGTH - 1); @@ -240,7 +301,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_019, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_020, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_026, TestSize.Level1) { std::vector rotationVector = {0.0, 0.0, 0.0}; std::vector rotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); @@ -253,7 +314,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_020, TestSize.Level1) } } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_021, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_027, TestSize.Level1) { std::vector rotationVector(ROTATION_VECTOR_LENGTH - 1); std::vector rotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); @@ -261,7 +322,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_021, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_022, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_028, TestSize.Level1) { std::vector rotationVector = {0.0, 0.0, 0.0}; std::vector rotationMatrix(ROTATION_VECTOR_LENGTH - 1); @@ -269,7 +330,25 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_022, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_023, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_029, TestSize.Level1) +{ + SEN_HILOGI("SensorAlgorithmTest_028 in"); + std::vector rotationVector = {0.0, 0.0, 0.0, 0.0, 0.0}; + std::vector rotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); + int32_t ret = sensorAlgorithm.CreateRotationMatrix(rotationVector, rotationMatrix); + ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); +} + +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_030, TestSize.Level1) +{ + SEN_HILOGI("SensorAlgorithmTest_029 in"); + std::vector rotationVector = {0.0, 0.0, 0.0, 0.0}; + std::vector rotationMatrix(FOUR_DIMENSIONAL_MATRIX_LENGTH); + int32_t ret = sensorAlgorithm.CreateRotationMatrix(rotationVector, rotationMatrix); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_031, TestSize.Level1) { std::vector gravity = {9.0, 9.0, 9.0}; std::vector geomagnetic = {30.0, 25.0, 41.0}; @@ -290,7 +369,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_023, TestSize.Level1) } } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_024, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_032, TestSize.Level1) { std::vector gravity(ROTATION_VECTOR_LENGTH - 1); std::vector geomagnetic = {30.0, 25.0, 41.0}; @@ -300,7 +379,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_024, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_025, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_033, TestSize.Level1) { std::vector gravity = {9.0, 9.0, 9.0}; std::vector geomagnetic(ROTATION_VECTOR_LENGTH - 1); @@ -310,7 +389,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_025, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_026, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_034, TestSize.Level1) { std::vector gravity = {9.0, 9.0, 9.0}; std::vector geomagnetic = {30.0, 25.0, 41.0}; @@ -320,7 +399,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_026, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_027, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_035, TestSize.Level1) { std::vector gravity = {9.0, 9.0, 9.0}; std::vector geomagnetic = {30.0, 25.0, 41.0}; @@ -330,7 +409,7 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_027, TestSize.Level1) ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); } -HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_028, TestSize.Level1) +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_036, TestSize.Level1) { GeomagneticField geomagneticField(80.0, 0.0, 0.0, 1580486400000); ASSERT_TRUE(fabs(geomagneticField.ObtainX() - 6570.3935546875) < EPS); @@ -341,5 +420,39 @@ HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_028, TestSize.Level1) ASSERT_TRUE(fabs(geomagneticField.ObtainLevelIntensity() - 6572.02294921875) < EPS); ASSERT_TRUE(fabs(geomagneticField.ObtainTotalIntensity() - 55000.0703125) < EPS); } + +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_037, TestSize.Level1) +{ + SEN_HILOGI("SensorAlgorithmTest_036 in"); + std::vector gravity = {0.1, 0.1, 0.1}; + std::vector geomagnetic = {30.0, 25.0, 41.0}; + std::vector rotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); + std::vector inclinationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); + int32_t ret = sensorAlgorithm.CreateRotationAndInclination(gravity, geomagnetic, rotationMatrix, inclinationMatrix); + ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); +} + +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_038, TestSize.Level1) +{ + SEN_HILOGI("SensorAlgorithmTest_037 in"); + std::vector gravity = {9.0, 9.0, 9.0}; + std::vector geomagnetic = {9.0, 9.0, 9.0}; + std::vector rotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); + std::vector inclinationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); + int32_t ret = sensorAlgorithm.CreateRotationAndInclination(gravity, geomagnetic, rotationMatrix, inclinationMatrix); + ASSERT_EQ(ret, OHOS::Sensors::PARAMETER_ERROR); +} + +HWTEST_F(SensorAlgorithmTest, SensorAlgorithmTest_039, TestSize.Level1) +{ + SEN_HILOGI("SensorAlgorithmTest_038 in"); + std::vector gravity = {9.0, 9.0, 9.0}; + std::vector geomagnetic = {30.0, 25.0, 41.0}; + std::vector rotationMatrix(FOUR_DIMENSIONAL_MATRIX_LENGTH); + std::vector inclinationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); + int32_t ret = sensorAlgorithm.CreateRotationAndInclination(gravity, geomagnetic, rotationMatrix, inclinationMatrix); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + } // namespace Sensors } // namespace OHOS diff --git a/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js b/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js index 37bc1313517ced30d86a0d7fa4ae1842502c4def..ca9326f94b89a13f1fd991f857c3f3a876ef056b 100644 --- a/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js +++ b/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js @@ -81,7 +81,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -129,7 +129,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -173,7 +173,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -221,7 +221,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -269,7 +269,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -313,7 +313,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -356,7 +356,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -405,7 +405,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -457,7 +457,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -506,7 +506,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 diff --git a/test/unittest/interfaces/js/sensor/common/CommonConstants.js b/test/unittest/interfaces/js/sensor/common/CommonConstants.js index fb6a2a2e49026c5982222d9a3d6e2eb445a0c824..abc4a087105ae189b34e200bfd7427cd537b8806 100644 --- a/test/unittest/interfaces/js/sensor/common/CommonConstants.js +++ b/test/unittest/interfaces/js/sensor/common/CommonConstants.js @@ -43,12 +43,12 @@ export default class CommonConstants { static SERVICE_EXCEPTION_CODE = 14500101; /** - * Exception code of sensorId no support + * Exception code of sensor not supported */ static SENSOR_NO_SUPPORT_CODE = 14500102; /** - * eps + * Eps */ static EPS = 0.01; diff --git a/test/unittest/interfaces/js/sensor/config.json b/test/unittest/interfaces/js/sensor/config.json index aabb3f4b8a5544b29581e64aedf217387cef1dfd..435079f98c0281c4efd6a1517338ce41b1942a05 100644 --- a/test/unittest/interfaces/js/sensor/config.json +++ b/test/unittest/interfaces/js/sensor/config.json @@ -57,7 +57,8 @@ "name": ".MyApplication", "deviceType": [ "default", - "tablet" + "tablet", + "2inl" ], "distro": { "deliveryWithInstall": true, diff --git a/test/unittest/interfaces/kits/sensor_native_test.cpp b/test/unittest/interfaces/kits/sensor_native_test.cpp index 650165dab01a41b74001ec4bb2202d201ecdf31f..00fcb0606d5245823ca5f1ab26d02b282d0d0427 100644 --- a/test/unittest/interfaces/kits/sensor_native_test.cpp +++ b/test/unittest/interfaces/kits/sensor_native_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-2024 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 @@ -42,7 +42,7 @@ constexpr int64_t INVALID_VALUE = -1; constexpr float INVALID_RESOLUTION = -1.0F; Sensor_Subscriber *g_user = nullptr; std::atomic_bool g_existAmbientLight = false; -} // namespace +} // namespace class SensorAgentTest : public testing::Test { public: @@ -111,6 +111,27 @@ void SensorDataCallbackImpl(Sensor_Event *event) } } +void SensorDataCallbackImpl1(Sensor_Event *event) +{ + if (event == nullptr) { + SEN_HILOGE("event is null"); + return; + } + int64_t *timestamp = nullptr; + int32_t ret = OH_SensorEvent_GetTimestamp(event, timestamp); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + Sensor_Type *sensorType = nullptr; + ret = OH_SensorEvent_GetType(event, sensorType); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + Sensor_Accuracy *accuracy = nullptr; + ret = OH_SensorEvent_GetAccuracy(event, accuracy); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + float *data = nullptr; + uint32_t *length = nullptr; + ret = OH_SensorEvent_GetData(event, &data, length); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); +} + HWTEST_F(SensorAgentTest, OH_Sensor_GetInfos_001, TestSize.Level1) { SEN_HILOGI("OH_Sensor_GetInfos_001 in"); @@ -153,12 +174,175 @@ HWTEST_F(SensorAgentTest, OH_Sensor_GetInfos_001, TestSize.Level1) HWTEST_F(SensorAgentTest, OH_Sensor_GetInfos_002, TestSize.Level1) { - SEN_HILOGI("OH_Sensor_GetInfos_003 in"); + SEN_HILOGI("OH_Sensor_GetInfos_002 in"); Sensor_Info *sensors { nullptr }; int32_t ret = OH_Sensor_GetInfos(&sensors, nullptr); ASSERT_NE(ret, SENSOR_SUCCESS); } +HWTEST_F(SensorAgentTest, OH_Sensor_GetInfos_003, TestSize.Level1) +{ + SEN_HILOGE("OH_Sensor_GetInfos_003 in"); + uint32_t count = 0; + int32_t ret = OH_Sensor_GetInfos(nullptr, &count); + ASSERT_EQ(ret, SENSOR_SUCCESS); + ASSERT_NE(0, count); + + auto sensors = new Sensor_Info *[count]; + for (uint32_t i = 0; i < count; ++i) { + if (sensors[i] != nullptr) { + sensors[i] = nullptr; + } + } + ret = OH_Sensor_GetInfos(sensors, &count); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + ret = OH_Sensor_DestroyInfos(sensors, count); + ASSERT_EQ(ret, SENSOR_SUCCESS); +} + +HWTEST_F(SensorAgentTest, OH_Sensor_GetInfos_004, TestSize.Level1) +{ + SEN_HILOGE("OH_Sensor_GetInfos_004 in"); + uint32_t count = 0; + int32_t ret = OH_Sensor_GetInfos(nullptr, &count); + ASSERT_EQ(ret, SENSOR_SUCCESS); + ASSERT_NE(0, count); + Sensor_Info **sensors = OH_Sensor_CreateInfos(count); + ASSERT_NE(sensors, nullptr); + char sensorName[SENSOR_NAME_LENGTH_MAX] = {}; + uint32_t length = SENSOR_NAME_LENGTH_MAX; + + auto sensors1 = new Sensor_Info *[count]; + for (uint32_t i = 0; i < count; ++i) { + if (sensors1[i] != nullptr) { + sensors1[i] = nullptr; + } + } + ret = OH_SensorInfo_GetName(sensors1[0], sensorName, &length); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + ret = OH_Sensor_DestroyInfos(sensors1, count); + ASSERT_EQ(ret, SENSOR_SUCCESS); + + char *sensorName1 = nullptr; + ret = OH_SensorInfo_GetName(sensors[0], sensorName1, &length); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + uint32_t *length1 = nullptr; + ret = OH_SensorInfo_GetName(sensors[0], sensorName, length1); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + ret = OH_Sensor_DestroyInfos(sensors, count); + ASSERT_EQ(ret, SENSOR_SUCCESS); +} + +HWTEST_F(SensorAgentTest, OH_Sensor_GetInfos_005, TestSize.Level1) +{ + SEN_HILOGE("OH_Sensor_GetInfos_005 in"); + uint32_t count = 0; + int32_t ret = OH_Sensor_GetInfos(nullptr, &count); + ASSERT_EQ(ret, SENSOR_SUCCESS); + ASSERT_NE(0, count); + Sensor_Info **sensors = OH_Sensor_CreateInfos(count); + ASSERT_NE(sensors, nullptr); + char sensorName[SENSOR_NAME_LENGTH_MAX] = {}; + uint32_t length = SENSOR_NAME_LENGTH_MAX; + + ret = OH_SensorInfo_GetName(sensors[0], sensorName, &length); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + ret = OH_Sensor_GetInfos(sensors, &count); + length = 0; + ret = OH_SensorInfo_GetName(sensors[0], sensorName, &length); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + ret = OH_Sensor_DestroyInfos(sensors, count); + ASSERT_EQ(ret, SENSOR_SUCCESS); +} + +HWTEST_F(SensorAgentTest, OH_Sensor_GetInfos_006, TestSize.Level1) +{ + SEN_HILOGE("OH_Sensor_GetInfos_006 in"); + uint32_t count = 0; + int32_t ret = OH_Sensor_GetInfos(nullptr, &count); + ASSERT_EQ(ret, SENSOR_SUCCESS); + ASSERT_NE(0, count); + Sensor_Info **sensors = OH_Sensor_CreateInfos(count); + ASSERT_NE(sensors, nullptr); + char vendorName[SENSOR_NAME_LENGTH_MAX] = {}; + uint32_t length = SENSOR_NAME_LENGTH_MAX; + + auto sensors1 = new Sensor_Info *[count]; + for (uint32_t i = 0; i < count; ++i) { + if (sensors1[i] != nullptr) { + sensors1[i] = nullptr; + } + } + ret = OH_SensorInfo_GetVendorName(sensors1[0], vendorName, &length); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + ret = OH_Sensor_DestroyInfos(sensors1, count); + ASSERT_EQ(ret, SENSOR_SUCCESS); + + char *vendorName1 = nullptr; + ret = OH_SensorInfo_GetVendorName(sensors[0], vendorName1, &length); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + uint32_t *length1 = nullptr; + ret = OH_SensorInfo_GetVendorName(sensors[0], vendorName, length1); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + ret = OH_Sensor_DestroyInfos(sensors, count); + ASSERT_EQ(ret, SENSOR_SUCCESS); +} + +HWTEST_F(SensorAgentTest, OH_Sensor_GetInfos_007, TestSize.Level1) +{ + SEN_HILOGE("OH_Sensor_GetInfos_007 in"); + uint32_t count = 0; + int32_t ret = OH_Sensor_GetInfos(nullptr, &count); + ASSERT_EQ(ret, SENSOR_SUCCESS); + ASSERT_NE(0, count); + Sensor_Info **sensors = OH_Sensor_CreateInfos(count); + ASSERT_NE(sensors, nullptr); + char sensorName[SENSOR_NAME_LENGTH_MAX] = {}; + uint32_t length = SENSOR_NAME_LENGTH_MAX; + + ret = OH_SensorInfo_GetVendorName(sensors[0], sensorName, &length); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + ret = OH_Sensor_GetInfos(sensors, &count); + length = 0; + ret = OH_SensorInfo_GetVendorName(sensors[0], sensorName, &length); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + ret = OH_Sensor_DestroyInfos(sensors, count); + ASSERT_EQ(ret, SENSOR_SUCCESS); +} + +HWTEST_F(SensorAgentTest, OH_Sensor_GetInfos_008, TestSize.Level1) +{ + SEN_HILOGE("OH_Sensor_GetInfos_008 in"); + uint32_t count = 0; + OH_Sensor_GetInfos(nullptr, &count); + auto sensors = new Sensor_Info *[count]; + + Sensor_Type *sensorType = nullptr; + int32_t ret = OH_SensorInfo_GetType(sensors[0], sensorType); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + float *resolution = nullptr; + ret = OH_SensorInfo_GetResolution(sensors[0], resolution); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + int64_t *minSamplePeriod = nullptr; + ret = OH_SensorInfo_GetMinSamplingInterval(sensors[0], minSamplePeriod); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + int64_t *maxSamplePeriod = nullptr; + ret = OH_SensorInfo_GetMaxSamplingInterval(sensors[0], maxSamplePeriod); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); +} + HWTEST_F(SensorAgentTest, OH_Sensor_Subscribe_001, TestSize.Level1) { SEN_HILOGI("OH_Sensor_Subscribe_001 in"); @@ -259,6 +443,82 @@ HWTEST_F(SensorAgentTest, OH_Sensor_Subscribe_004, TestSize.Level1) } } +HWTEST_F(SensorAgentTest, OH_Sensor_Subscribe_005, TestSize.Level1) +{ + SEN_HILOGI("OH_Sensor_Subscribe_005 in"); + g_user = OH_Sensor_CreateSubscriber(); + int32_t ret = OH_SensorSubscriber_SetCallback(g_user, SensorDataCallbackImpl); + ASSERT_EQ(ret, SENSOR_SUCCESS); + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); + ret = OH_SensorSubscriptionAttribute_SetSamplingInterval(attr, SENSOR_SAMPLE_PERIOD); + ASSERT_EQ(ret, SENSOR_SUCCESS); + ret = OH_Sensor_Subscribe(id, attr, g_user); + ASSERT_EQ(ret, SENSOR_SERVICE_EXCEPTION); +} + +HWTEST_F(SensorAgentTest, OH_Sensor_Subscribe_006, TestSize.Level1) +{ + SEN_HILOGI("OH_Sensor_Subscribe_006 in"); + if (g_existAmbientLight) { + g_user = OH_Sensor_CreateSubscriber(); + int32_t ret = OH_SensorSubscriber_SetCallback(g_user, SensorDataCallbackImpl); + ASSERT_EQ(ret, SENSOR_SUCCESS); + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + ret = OH_SensorSubscriptionId_SetType(id, SENSOR_ID); + ASSERT_EQ(ret, SENSOR_SUCCESS); + Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); + ret = OH_Sensor_Subscribe(id, attr, g_user); + ASSERT_EQ(ret, SENSOR_SERVICE_EXCEPTION); + } +} + +HWTEST_F(SensorAgentTest, OH_Sensor_Subscribe_007, TestSize.Level1) +{ + SEN_HILOGI("OH_Sensor_Subscribe_007 in"); + g_user = OH_Sensor_CreateSubscriber(); + int32_t ret = OH_SensorSubscriber_SetCallback(g_user, SensorDataCallbackImpl); + ASSERT_EQ(ret, SENSOR_SUCCESS); + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + ret = OH_Sensor_Unsubscribe(id, g_user); + ASSERT_EQ(ret, SENSOR_SERVICE_EXCEPTION); +} + +HWTEST_F(SensorAgentTest, OH_Sensor_Subscribe_008, TestSize.Level1) +{ + SEN_HILOGI("OH_Sensor_Subscribe_008 in"); + if (g_existAmbientLight) { + g_user = OH_Sensor_CreateSubscriber(); + int32_t ret = OH_SensorSubscriber_SetCallback(g_user, SensorDataCallbackImpl1); + ASSERT_EQ(ret, SENSOR_SUCCESS); + + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + ret = OH_SensorSubscriptionId_SetType(id, SENSOR_ID); + ASSERT_EQ(ret, SENSOR_SUCCESS); + + Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); + ret = OH_SensorSubscriptionAttribute_SetSamplingInterval(attr, SENSOR_SAMPLE_PERIOD); + ASSERT_EQ(ret, SENSOR_SUCCESS); + + ret = OH_Sensor_Subscribe(id, attr, g_user); + ASSERT_EQ(ret, SENSOR_SUCCESS); + + std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME_MS)); + ret = OH_Sensor_Unsubscribe(id, g_user); + ASSERT_EQ(ret, SENSOR_SUCCESS); + if (id != nullptr) { + OH_Sensor_DestroySubscriptionId(id); + } + if (attr != nullptr) { + OH_Sensor_DestroySubscriptionAttribute(attr); + } + if (g_user != nullptr) { + OH_Sensor_DestroySubscriber(g_user); + g_user = nullptr; + } + } +} + HWTEST_F(SensorAgentTest, OH_Sensor_Unsubscribe_001, TestSize.Level1) { SEN_HILOGI("OH_Sensor_Unsubscribe_001 in"); @@ -314,6 +574,35 @@ HWTEST_F(SensorAgentTest, OH_SensorSubscriptionId_GetType_002, TestSize.Level1) } } +HWTEST_F(SensorAgentTest, OH_SensorSubscriptionId_GetType_003, TestSize.Level1) +{ + SEN_HILOGI("OH_SensorSubscriptionId_GetType_003 in"); + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + Sensor_Type type; + int32_t ret = OH_SensorSubscriptionId_GetType(id, &type); + ASSERT_EQ(ret, SENSOR_SUCCESS); + if (id != nullptr) { + OH_Sensor_DestroySubscriptionId(id); + } +} + + +HWTEST_F(SensorAgentTest, OH_SensorSubscriptionId_GetType_004, TestSize.Level1) +{ + SEN_HILOGI("OH_SensorSubscriptionId_GetType_004 in"); + Sensor_SubscriptionId *id = nullptr; + + int32_t ret = OH_Sensor_DestroySubscriptionId(id); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + Sensor_SubscriptionAttribute *attr = nullptr; + ret = OH_Sensor_DestroySubscriptionAttribute(attr); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); + + ret = OH_Sensor_DestroySubscriber(g_user); + ASSERT_EQ(ret, SENSOR_PARAMETER_ERROR); +} + HWTEST_F(SensorAgentTest, OH_SensorSubscriptionAttribute_SetSamplingInterval_001, TestSize.Level1) { @@ -357,6 +646,19 @@ HWTEST_F(SensorAgentTest, OH_SensorSubscriptionAttribute_GetSamplingInterval_002 } } +HWTEST_F(SensorAgentTest, OH_SensorSubscriptionAttribute_GetSamplingInterval_003, + TestSize.Level1) +{ + SEN_HILOGI("OH_SensorSubscriptionAttribute_GetSamplingInterval_003 in"); + Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); + int64_t samplingInterval = 0; + int32_t ret = OH_SensorSubscriptionAttribute_GetSamplingInterval(attr, &samplingInterval); + ASSERT_EQ(ret, SENSOR_SUCCESS); + if (attr != nullptr) { + OH_Sensor_DestroySubscriptionAttribute(attr); + } +} + HWTEST_F(SensorAgentTest, OH_SensorSubscriber_SetCallback_001, TestSize.Level1) { SEN_HILOGI("OH_SensorSubscriber_SetCallback_001 in"); @@ -390,5 +692,17 @@ HWTEST_F(SensorAgentTest, OH_SensorSubscriber_GetCallback_002, TestSize.Level1) OH_Sensor_DestroySubscriber(g_user); } } -} // namespace Sensors -} // namespace OHOS + +HWTEST_F(SensorAgentTest, OH_SensorSubscriber_GetCallback_003, TestSize.Level1) +{ + SEN_HILOGI("OH_SensorSubscriber_GetCallback_003 in"); + g_user = OH_Sensor_CreateSubscriber(); + Sensor_EventCallback callback; + int32_t ret = OH_SensorSubscriber_GetCallback(g_user, &callback); + ASSERT_EQ(ret, SENSOR_SUCCESS); + if (g_user != nullptr) { + OH_Sensor_DestroySubscriber(g_user); + } +} +} // namespace Sensors +} // namespace OHOS diff --git a/utils/common/BUILD.gn b/utils/common/BUILD.gn index 48bce26e0b22d0f7f21321a598905ed917336150..0d522496a5c8929deed3cd9e944219f72686bf9f 100644 --- a/utils/common/BUILD.gn +++ b/utils/common/BUILD.gn @@ -18,6 +18,7 @@ ohos_shared_library("libsensor_utils") { sources = [ "src/active_info.cpp", "src/permission_util.cpp", + "src/print_sensor_data.cpp", "src/report_data_callback.cpp", "src/sensor.cpp", "src/sensor_basic_data_channel.cpp", diff --git a/utils/common/include/print_sensor_data.h b/utils/common/include/print_sensor_data.h new file mode 100644 index 0000000000000000000000000000000000000000..3997069234ddcef3e0be78c0dc3b975e0449ef7e --- /dev/null +++ b/utils/common/include/print_sensor_data.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2024 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 PRINT_SENSOR_DATA +#define PRINT_SENSOR_DATA + +#include + +#include "singleton.h" + +#include "sensor_agent_type.h" +#include "sensor_data_event.h" + +namespace OHOS { +namespace Sensors { + + +class PrintSensorData : public Singleton { +public: + PrintSensorData() = default; + virtual ~PrintSensorData() {}; + void ControlSensorClientPrint(const RecordSensorCallback callback, const SensorEvent &event); + void ControlSensorHdiPrint(const SensorData &sensorData); + void ResetHdiCounter(int32_t sensorId); + bool IsContinuousType(int32_t sensorId); + void SavePrintUserInfo(const RecordSensorCallback callback); + void RemovePrintUserInfo(const RecordSensorCallback callback); + +private: + void PrintClientData(const SensorEvent &event); + void PrintHdiData(const SensorData &sensorData); + int32_t GetDataDimension(int32_t sensorId); + struct LogPrintInfo { + int32_t count { 0 }; + int64_t lastTime { 0 }; + }; + std::mutex hdiLoginfoMutex_; + std::mutex clientLoginfoMutex_; + LogPrintInfo info_; + std::map hdiLoginfo_ = { + {SENSOR_TYPE_ID_ACCELEROMETER, info_}, + {SENSOR_TYPE_ID_GYROSCOPE, info_}, + {SENSOR_TYPE_ID_POSTURE, info_}, + {SENSOR_TYPE_ID_AMBIENT_LIGHT, info_}, + {SENSOR_TYPE_ID_AMBIENT_LIGHT1, info_}, + {SENSOR_TYPE_ID_MAGNETIC_FIELD, info_}, + }; + std::map clientLoginfo_; +}; +} // namespace Sensors +} // namespace OHOS +#endif // PRINT_SENSOR_DATA diff --git a/utils/common/src/print_sensor_data.cpp b/utils/common/src/print_sensor_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45881fdbdc1af297a11ec018233f9254de4f3e17 --- /dev/null +++ b/utils/common/src/print_sensor_data.cpp @@ -0,0 +1,213 @@ +/* + * Copyright (c) 2024 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 "print_sensor_data.h" + +#include +#include + +#include "sensor_errors.h" + +#undef LOG_TAG +#define LOG_TAG "PrintSensorData" + +namespace OHOS { +namespace Sensors { +namespace { +enum { + ONE_DIMENSION = 1, + TWO_DIMENSION = 2, + THREE_DIMENSION = 3, + SEVEN_DIMENSION = 7, + DEFAULT_DIMENSION = 16 +}; +constexpr int64_t LOG_INTERVAL = 60000000000L; +constexpr int32_t FIRST_PRINT_TIMES = 20; +constexpr float LOG_FORMAT_DIVIDER = 1e9f; + +const std::vector g_triggerSensorType = { + SENSOR_TYPE_ID_HALL_EXT, + SENSOR_TYPE_ID_PROXIMITY, + SENSOR_TYPE_ID_HALL, + SENSOR_TYPE_ID_WEAR_DETECTION, +}; +const std::vector g_continuousSensorType = { + SENSOR_TYPE_ID_ACCELEROMETER, + SENSOR_TYPE_ID_POSTURE, + SENSOR_TYPE_ID_AMBIENT_LIGHT, + SENSOR_TYPE_ID_AMBIENT_LIGHT1, + SENSOR_TYPE_ID_GYROSCOPE, + SENSOR_TYPE_ID_MAGNETIC_FIELD, +}; +} + +void PrintSensorData::ControlSensorHdiPrint(const SensorData &sensorData) +{ + auto triggerIt = std::find(g_triggerSensorType.begin(), g_triggerSensorType.end(), sensorData.sensorTypeId); + if (triggerIt != g_triggerSensorType.end()) { + PrintHdiData(sensorData); + } + std::lock_guard hdiLoginfoLock(hdiLoginfoMutex_); + auto it = hdiLoginfo_.find(sensorData.sensorTypeId); + if (it == hdiLoginfo_.end()) { + return; + } + if (it->second.count < FIRST_PRINT_TIMES) { + PrintHdiData(sensorData); + if (it->second.count == FIRST_PRINT_TIMES - 1) { + it->second.lastTime = sensorData.timestamp; + } + it->second.count++; + } else { + if (sensorData.timestamp - it->second.lastTime >= LOG_INTERVAL) { + PrintHdiData(sensorData); + it->second.lastTime = sensorData.timestamp; + } + } +} + +void PrintSensorData::PrintHdiData(const SensorData &sensorData) +{ + std::string str; + str += "sensorId: " + std::to_string(sensorData.sensorTypeId) + ", "; + str += "timestamp: " + std::to_string(sensorData.timestamp / LOG_FORMAT_DIVIDER) + ", "; + int32_t dataDim = GetDataDimension(sensorData.sensorTypeId); + auto data = reinterpret_cast(sensorData.data); + CHKPV(data); + for (int32_t i = 0; i < dataDim; ++i) { + str.append(std::to_string(*data)); + if (i != dataDim - 1) { + str.append(", "); + } + ++data; + } + str.append("\n"); + SEN_HILOGI("SensorData: %{public}s", str.c_str()); +} + +int32_t PrintSensorData::GetDataDimension(int32_t sensorId) +{ + switch (sensorId) { + case SENSOR_TYPE_ID_HALL: + case SENSOR_TYPE_ID_PROXIMITY: + case SENSOR_TYPE_ID_WEAR_DETECTION: + return ONE_DIMENSION; + case SENSOR_TYPE_ID_HALL_EXT: + return TWO_DIMENSION; + case SENSOR_TYPE_ID_POSTURE: + return SEVEN_DIMENSION; + case SENSOR_TYPE_ID_AMBIENT_LIGHT: + case SENSOR_TYPE_ID_AMBIENT_LIGHT1: + case SENSOR_TYPE_ID_ACCELEROMETER: + case SENSOR_TYPE_ID_GYROSCOPE: + case SENSOR_TYPE_ID_MAGNETIC_FIELD: + return THREE_DIMENSION; + default: + SEN_HILOGW("Unknown sensorId:%{public}d, size:%{public}d", sensorId, DEFAULT_DIMENSION); + return DEFAULT_DIMENSION; + } +} + +void PrintSensorData::ControlSensorClientPrint(const RecordSensorCallback callback, const SensorEvent &event) +{ + auto triggerIt = std::find(g_triggerSensorType.begin(), g_triggerSensorType.end(), event.sensorTypeId); + if (triggerIt != g_triggerSensorType.end()) { + PrintClientData(event); + } + + auto continuosIt = std::find(g_continuousSensorType.begin(), g_continuousSensorType.end(), event.sensorTypeId); + if (continuosIt == g_continuousSensorType.end()) { + return; + } + std::lock_guard clientLoginfoLock(clientLoginfoMutex_); + auto it = clientLoginfo_.find(callback); + if (it == clientLoginfo_.end()) { + return; + } + if (it->second.count < FIRST_PRINT_TIMES) { + PrintClientData(event); + if (it->second.count == FIRST_PRINT_TIMES - 1) { + it->second.lastTime = event.timestamp; + } + it->second.count++; + } else { + if (event.timestamp - it->second.lastTime >= LOG_INTERVAL) { + PrintClientData(event); + it->second.lastTime = event.timestamp; + } + } +} + +void PrintSensorData::PrintClientData(const SensorEvent &event) +{ + std::string str; + str += "sensorId: " + std::to_string(event.sensorTypeId) + ", "; + str += "timestamp: " + std::to_string(event.timestamp / LOG_FORMAT_DIVIDER) + ", "; + int32_t dataDim = GetDataDimension(event.sensorTypeId); + auto data = reinterpret_cast(event.data); + CHKPV(data); + for (int32_t i = 0; i < dataDim; ++i) { + str.append(std::to_string(*data)); + if (i != dataDim - 1) { + str.append(", "); + } + ++data; + } + str.append("\n"); + SEN_HILOGI("SensorData: %{public}s", str.c_str()); +} + +bool PrintSensorData::IsContinuousType(int32_t sensorId) +{ + return std::find(g_continuousSensorType.begin(), g_continuousSensorType.end(), + sensorId) != g_continuousSensorType.end(); +} + +void PrintSensorData::SavePrintUserInfo(const RecordSensorCallback callback) +{ + CHKPV(callback); + std::lock_guard clientLoginfoLock(clientLoginfoMutex_); + if (clientLoginfo_.find(callback) != clientLoginfo_.end()) { + return; + } + LogPrintInfo info; + auto status = clientLoginfo_.insert(std::make_pair(callback, info)); + if (!status.second) { + SEN_HILOGD("callback has been saved"); + } +} + +void PrintSensorData::RemovePrintUserInfo(const RecordSensorCallback callback) +{ + CHKPV(callback); + std::lock_guard clientLoginfoLock(clientLoginfoMutex_); + if (clientLoginfo_.find(callback) == clientLoginfo_.end()) { + return; + } + clientLoginfo_.erase(callback); +} + +void PrintSensorData::ResetHdiCounter(int32_t sensorId) +{ + std::lock_guard hdiLoginfoLock(hdiLoginfoMutex_); + auto it = hdiLoginfo_.find(sensorId); + if (it == hdiLoginfo_.end()) { + return; + } + it->second.count = 0; + it->second.lastTime = 0; +} +} // namespace Sensors +} // namespace OHOS diff --git a/utils/common/src/report_data_callback.cpp b/utils/common/src/report_data_callback.cpp index 12e882fd526e53dfb271899d810975d362f0de0b..1eb2aac58e30deb03b3862bebf979b56854b44ac 100644 --- a/utils/common/src/report_data_callback.cpp +++ b/utils/common/src/report_data_callback.cpp @@ -64,16 +64,16 @@ int32_t ReportDataCallback::ReportEventCallback(SensorData *sensorData, sptreventsBuf_.circularBuf[cb->eventsBuf_.writePosition] = *sensorData; cb->eventsBuf_.writePosition += 1; } - if (leftSize < 1) { - cb->eventsBuf_.readPos = cb->eventsBuf_.writePosition; - } cb->eventsBuf_.eventNum += 1; if (cb->eventsBuf_.eventNum >= CIRCULAR_BUF_LEN) { cb->eventsBuf_.eventNum = CIRCULAR_BUF_LEN; } - if (cb->eventsBuf_.writePosition == CIRCULAR_BUF_LEN) { + if (cb->eventsBuf_.writePosition >= CIRCULAR_BUF_LEN) { cb->eventsBuf_.writePosition = 0; } + if (leftSize < 1) { + cb->eventsBuf_.readPos = cb->eventsBuf_.writePosition; + } return ERR_OK; } @@ -81,5 +81,5 @@ CircularEventBuf &ReportDataCallback::GetEventData() { return eventsBuf_; } -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS diff --git a/utils/ipc/BUILD.gn b/utils/ipc/BUILD.gn index 9bbc90d6e17fdd3fb34c8f19825587857a4f4364..a37332ae66b71c095bf6d6aaef5e4f1ba842a88c 100644 --- a/utils/ipc/BUILD.gn +++ b/utils/ipc/BUILD.gn @@ -37,7 +37,7 @@ ohos_shared_library("libsensor_ipc") { defines = sensor_default_defines - if (rust_socket_ipc) { + if (sensor_rust_socket_ipc) { deps = [ "$SUBSYSTEM_DIR/rust/utils/socket_ipc_rust_ffi:sensor_rust_util_ffi" ] } diff --git a/utils/ipc/src/stream_socket.cpp b/utils/ipc/src/stream_socket.cpp index 48c3fed9f86822f1eac7ac47f63e84ed4c536968..e59266ad0d0a464edd4974981fe784475302479a 100644 --- a/utils/ipc/src/stream_socket.cpp +++ b/utils/ipc/src/stream_socket.cpp @@ -52,7 +52,7 @@ void StreamSocket::OnReadPackets(CircleStreamBuffer &circBuf, StreamSocket::Pack PackHead *head = reinterpret_cast(buf); CHKPB(head); 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." + SEN_HILOGE("Packet header parsing error, and this error cannot be recovered. The buffer will be reset" " head->size:%{public}zu, unreadSize:%{public}zu", head->size, unreadSize); circBuf.Reset(); break; @@ -67,7 +67,7 @@ void StreamSocket::OnReadPackets(CircleStreamBuffer &circBuf, StreamSocket::Pack break; } if (!circBuf.SeekReadPos(pkt.GetPacketLength())) { - SEN_HILOGW("Set read position error, and this error cannot be recovered, and the buffer will be reset." + SEN_HILOGW("Set read position error, and this error cannot be recovered, and the buffer will be reset" " packetSize:%{public}zu, unreadSize:%{public}zu", pkt.GetPacketLength(), unreadSize); circBuf.Reset(); break; @@ -79,7 +79,7 @@ void StreamSocket::OnReadPackets(CircleStreamBuffer &circBuf, StreamSocket::Pack } } } -#endif // OHOS_BUILD_ENABLE_RUST +#endif // OHOS_BUILD_ENABLE_RUST void StreamSocket::Close() { @@ -104,5 +104,5 @@ int32_t StreamSocket::GetFd() const return fd_; #endif // OHOS_BUILD_ENABLE_RUST } -} // namespace Sensors -} // namespace OHOS \ No newline at end of file +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp b/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp index 11bdb3a878ebcba7f24ca97f7ea0849075269bea..2abedb2ff93a8f09597244ab74f91e3544647cc8 100644 --- a/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp +++ b/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp @@ -27,7 +27,7 @@ namespace Sensors { namespace { constexpr int32_t SPECTRUM_COUNT_MAX { 8192 }; constexpr int32_t MAX_FFT_SIZE { 10240 }; -} // namespace +} // namespace int32_t ConversionFFT::Init(const FFTInputPara &fftPara) { @@ -96,7 +96,7 @@ int32_t ConversionFFT::Process(const std::vector &values, int32_t &frame frameCount = 0; bool isFrameFull = false; size_t valuesSize = values.size(); - for (size_t j = 0; j < valuesSize; ++j) { + for (size_t j = 0; j < valuesSize; j++) { // add value to buffer at current pos if (pos_ < static_cast(fftResult_.buffer.size())) { fftResult_.buffer[pos_++] = static_cast(values[j]); @@ -248,7 +248,7 @@ int32_t ConversionOctave::Init(float samplingRate, int32_t nBandsInTheFFT, int32 // guessing that this is where it is (or possibly spectrumFrequencySpan/2?) // ... either way it's probably close enough for these purposes float spectrumFreq = spectrumFrequencySpan_; - for (int32_t speIdx = 0; speIdx < nSpectrum_; ++speIdx) { + for (int32_t speIdx = 0; speIdx < nSpectrum_; speIdx++) { while (spectrumFreq > averageFreq) { ++avgIdx; averageFreq *= averageFrequencyIncrement_; @@ -268,6 +268,8 @@ int32_t ConversionOctave::Init(float samplingRate, int32_t nBandsInTheFFT, int32 auto peakHoldTimes = new (std::nothrow) int32_t[nAverages_]; CHKPR(peakHoldTimes, Sensors::ERROR); std::shared_ptr peakHoldTimesShared(peakHoldTimes, std::default_delete()); + peakHoldTimes_ = std::move(peakHoldTimesShared); + peakHoldTime_ = 0; peakDecayRate_ = 0.9F; linearEQIntercept_ = 1.0F; @@ -288,12 +290,12 @@ int32_t ConversionOctave::Calculate(const std::vector &fftData) int32_t lastAvgIdx = 0; // tracks when we've crossed into a new averaging bin, so store current average float sum = 0.0F; // running total of spectrum data int32_t count = 0; // count of spectrums accumulated (for averaging) - for (int32_t speIdx = 0; speIdx < nSpectrum_; ++speIdx) { + for (int32_t speIdx = 0; speIdx < nSpectrum_; speIdx++) { ++count; sum += (fftData[speIdx] * (linearEQIntercept_ + speIdx * linearEQSlope_)); int32_t avgIdx = *(spe2avg_.get() + speIdx); if (avgIdx != lastAvgIdx) { - for (int32_t j = lastAvgIdx; j < avgIdx; ++j) { + for (int32_t j = lastAvgIdx; j < avgIdx; j++) { *(averages_.get() + j) = sum / static_cast(count); } count = 0; @@ -322,5 +324,5 @@ int32_t ConversionOctave::Calculate(const std::vector &fftData) } return Sensors::SUCCESS; } -} // namespace Sensors -} // namespace OHOS \ No newline at end of file +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp b/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp index a1e282a693420ad2ce1fa69581cd4f534db9cee2..7f0bbcf74f0009e5332e3269ebc3c5436a04fe47 100644 --- a/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp +++ b/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp @@ -28,7 +28,7 @@ namespace Sensors { namespace { constexpr double BANDS_MIN_THRESHOLD { 0.000001 }; constexpr uint32_t MEL_FILTERS_OR_COEFFS_MAX { 4096 * 4096 }; -} // namespace +} // namespace int32_t ConversionMfcc::HandleMelFilterAndLogSquare(const std::vector &powerSpectrum) { @@ -223,16 +223,15 @@ int32_t ConversionMfcc::FiltersMel(int32_t nFft, MfccInputPara para, fMax = sr / 2.0; } size_t nMels = static_cast(para.nMels); - double fMin = para.minFreq; frmCount = nFft / 2; std::vector basis(nMels * frmCount, 0.0); // generate mel frequencies. + double fMin = para.minFreq; double minMel = OHOS::Sensors::ConvertHtkMel(fMin); double maxMel = OHOS::Sensors::ConvertHtkMel(fMax); std::vector filterHzPos(nMels + 2); double stepMel = (maxMel - minMel) / (nMels + 1); double stepHz = static_cast(sr) / nFft; - double nextMel = minMel; for (size_t i = 0; i < (nMels + 2); ++i) { filterHzPos[i] = OHOS::Sensors::ConvertHtkHz(nextMel); @@ -261,7 +260,7 @@ int32_t ConversionMfcc::FiltersMel(int32_t nFft, MfccInputPara para, } } melBasis = OHOS::Sensors::TransposeMatrix(nMels, basis); - return melBasis.empty() ? Sensor::ERROR : Sensors::SUCCESS; + return melBasis.empty() ? Sensors::ERROR : Sensors::SUCCESS; } -} // namespace Sensors -} // namespace OHOS \ No newline at end of file +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/vibration_convert/core/native/src/vibration_convert_core.cpp b/vibration_convert/core/native/src/vibration_convert_core.cpp index 571cca78d06b291ad88d097230f339023668d46f..bfa93cf83b6d760ed49dc456f4a56e718a748904 100644 --- a/vibration_convert/core/native/src/vibration_convert_core.cpp +++ b/vibration_convert/core/native/src/vibration_convert_core.cpp @@ -64,7 +64,7 @@ constexpr double AMPLITUDE_DB_MAX { 1.0 }; constexpr int32_t ADSR_BOUNDARY_STATUS_NONE { 0 }; constexpr int32_t ADSR_BOUNDARY_STATUS_ONE { 1 }; constexpr int32_t ADSR_BOUNDARY_STATUS_BOTH { 2 }; -} // namespace +} // namespace int32_t VibrationConvertCore::GetAudioData() { @@ -109,6 +109,7 @@ int32_t VibrationConvertCore::GetAudioData() } return Sensors::SUCCESS; } + int32_t VibrationConvertCore::ConvertAudioToHaptic(const AudioSetting &audioSetting, const std::vector &audioData, std::vector &hapticEvents) { @@ -293,7 +294,7 @@ double VibrationConvertCore::CalcRmsLowerData(size_t dataSize, const std::vector if (newDrwIdx.size() > 0) { for (int32_t i = 0; i < RMSE_LOWDELTA_ITERATION_TIMES; i++) { int32_t j = newDrwIdx[0]; - lowerDelta = rmseRange * (RMSE_LOWDELTA_RATIO_HIGH - i * RMSE_LOWDELTA_RATIO_STEP ) + rmseMin; + lowerDelta = rmseRange * (RMSE_LOWDELTA_RATIO_HIGH - i * RMSE_LOWDELTA_RATIO_STEP) + rmseMin; if ((rmse[j] > lowerDelta) || (rmse[j + 1] > lowerDelta)) { break; } @@ -542,7 +543,7 @@ int32_t VibrationConvertCore::ConvertTransientEvent(const std::vector &d IsolatedEnvelopeInfo isolatedEnvelopeInfo; int32_t ret = peakFinder_.ObtainTransientByAmplitude(data, isolatedEnvelopeInfo); if (ret != Sensors::SUCCESS) { - SEN_HILOGE("ObtainTransientByAmplitude failed."); + SEN_HILOGE("ObtainTransientByAmplitude failed"); return ret; } if (!isolatedEnvelopeInfo.isHaveContinuousEvent) { @@ -679,13 +680,13 @@ std::vector VibrationConvertCore::GetTransientEventFlags(const std::vector if ((i != 0) && (beginIdx < onsetIdxs[i - 1] * ENERGY_HOP_LEN)) { beginIdx = onsetIdxs[i - 1] * ENERGY_HOP_LEN; } - int32_t dataSize = static_cast(data.size()); + int32_t dataSize = static_cast(data.size()); if (endIdx >= dataSize) { endIdx = dataSize - 1; } std::vector localData; for (int32_t j = beginIdx; j <= endIdx; ++j) { - localData.push_back(data[i]); + localData.push_back(data[i]); } double unzeroDensity = 0.0; int32_t unzeroCount = 0; @@ -775,7 +776,7 @@ void VibrationConvertCore::TranslateAnchorPoint(const std::vector &l } void VibrationConvertCore::TranslateAnchorPoint(int32_t amplitudePeakPos, int32_t &litudePeakIdx, - ouble &litudePeakTime) + double &litudePeakTime) { bool useAbsTimeFlag = systemPara_.useAbsTimeFlag; amplitudePeakIdx = static_cast(round(1.0 * amplitudePeakPos / ENERGY_HOP_LEN)); @@ -1022,7 +1023,7 @@ void VibrationConvertCore::OutputAllContinuousEventByUnseg(const std::vector durations; FillDefaultContinuousEvents(rmseTimeNorm, times, durations); int32_t ret = InsertTransientEvent(rmseTimeNorm, transientIndex, transientEventFlags, - times, durations); + times, durations); if (ret != Sensors::SUCCESS) { SEN_HILOGE("InsertTransientEvent failed"); return; @@ -1030,7 +1031,7 @@ void VibrationConvertCore::OutputAllContinuousEventByUnseg(const std::vector continuousEvents; for (size_t i = 0; i < times.size(); i++) { continuousEvents.push_back(ContinuousEvent(times[i], durations[i], - intensityData[i].rmseIntensityNorm, freqNorm[i])); + intensityData[i].rmseIntensityNorm, freqNorm[i])); } MergeContinuousEvents(continuousEvents); } @@ -1196,5 +1197,5 @@ void VibrationConvertCore::AddContinuousEventData(const ContinuousEvent &continu { continuousEvents_.push_back(continuousEvent); } -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS diff --git a/vibration_convert/core/utils/include/audio_utils.h b/vibration_convert/core/utils/include/audio_utils.h index 57e3f681c4ad8e15530cf86bf7d387f3edc39e25..fa188cc94b1a166be6ea0c31a07f5440a3c26d18 100644 --- a/vibration_convert/core/utils/include/audio_utils.h +++ b/vibration_convert/core/utils/include/audio_utils.h @@ -34,7 +34,7 @@ namespace Sensors { namespace { constexpr double DB_TO_AMP_COEF { 0.05 }; constexpr double AMP_TO_DB_COEF { 20.0 }; -} // namespace +} // namespace /** *@brief Basic processing of audio, called by other modules. @@ -102,6 +102,6 @@ public: */ std::vector PadData(const std::vector &data, int32_t hopLength); }; -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS #endif \ No newline at end of file diff --git a/vibration_convert/core/utils/include/utils.h b/vibration_convert/core/utils/include/utils.h index 07689309dbbdb69263aa8f7964c13fa343b1778b..5cd0c385dc7624c3c2a88708ac4219b161554177 100644 --- a/vibration_convert/core/utils/include/utils.h +++ b/vibration_convert/core/utils/include/utils.h @@ -47,7 +47,7 @@ constexpr double F_THREE = 3.0; constexpr double SAMPLE_IN_MS = 1000.0; constexpr double INTERSITY_BOUNDARY_POINT = 0.25; constexpr double INTERSITY_NUMBER_BOUNDARY_POINT = 0.75; -} // namespace +} // namespace enum WindowType { WND_TYPE_BARTLETT = 1, @@ -56,9 +56,9 @@ enum WindowType { }; enum FilterMethod{ - LOW_RESONANT_FILTER = 1, - HIGH_RESONANT_FILTER = 2, - BAND_PASS_FILTER = 3, + LOW_RESONANT_FILTER = 1, + HIGH_RESONANT_FILTER = 2, + BAND_PASS_FILTER = 3, }; bool IsPowerOfTwo(uint32_t x); @@ -182,12 +182,6 @@ inline bool IsEqual(const T& left, const T& right) return (std::abs(left - right) <= std::numeric_limits::epsilon()); } -template -decltype(auto) MakeSharedArray(size_t size) -{ - return std::shared_ptr(new T[size], std::default_delete()); -} - inline double ConvertHtkMel(double frequencies) { double mels = (frequencies - MIN_F) / FSP; @@ -205,6 +199,6 @@ inline double ConvertHtkHz(double mels) } return freqs; } -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS #endif // CONVERSION_UTILS_H \ No newline at end of file diff --git a/vibration_convert/core/utils/src/utils.cpp b/vibration_convert/core/utils/src/utils.cpp index dded5ba1424c0f3cedb649f70048fce2c2dcccfc..71e9ee6a2abf9c4df36ff1d0ec0f0ad030fd8796 100644 --- a/vibration_convert/core/utils/src/utils.cpp +++ b/vibration_convert/core/utils/src/utils.cpp @@ -33,11 +33,11 @@ namespace OHOS { namespace Sensors { -namespace{ +namespace { constexpr double PERCENTAGE_RANGE = 100.0; constexpr int32_t VOICE_MIN_INTENSITY_NORM = 25; constexpr size_t MAX_SIZE = 26460000; -} // namespace +} // namespace bool IsPowerOfTwo(uint32_t x) { @@ -77,7 +77,7 @@ std::vector TransposeMatrix(size_t rows, const std::vector &valu size_t valuesSize = values.size(); SEN_HILOGD("valuesSize:%{public}zu", valuesSize); if ((rows == 0) || (valuesSize == 0) || (valuesSize > MAX_SIZE)) { - SEN_HILOGE("Parameter is invalid"); + SEN_HILOGE("Parameter error"); return {}; } std::vector dst(valuesSize, 0.0); @@ -100,7 +100,7 @@ int32_t UniqueIdx(const std::vector &idx, const std::vector &ti { CALL_LOG_ENTER; if (idx.size() != time.size()) { - SEN_HILOGE("Size of idx and time vectors not equal"); + SEN_HILOGE("size of idx and time vectors not equal"); return Sensors::ERROR; } int32_t oldIdxLen = static_cast(idx.size()); @@ -123,7 +123,7 @@ int32_t UniqueIdx(const std::vector &idx, const std::vector &ti ++i; } if (idxLen != oldIdxLen) { - SEN_HILOGI("idx unique process"); + SEN_HILOGI("Idx unique process"); } return Sensors::SUCCESS; } @@ -259,5 +259,5 @@ std::vector ObtainAmplitudeEnvelop(const std::vector &data, size } return enery; } -} // namespace Sensors -} // namespace OHOS \ No newline at end of file +} // namespace Sensors +} // namespace OHOS \ No newline at end of file