diff --git a/.github/workflows/spm-release.yml b/.github/workflows/spm-release.yml new file mode 100644 index 000000000..2fbd94ba1 --- /dev/null +++ b/.github/workflows/spm-release.yml @@ -0,0 +1,172 @@ +name: SPM release (xcframework) + +# On a published SDK release, build MATTelemetry.xcframework, upload it to the +# GitHub Release, and publish a 3-component SemVer tag for Swift Package Manager +# whose Package.swift binaryTarget points at the uploaded artifact + checksum. +# +# Why a separate tag: the SDK's own release tags are 4-component (vX.Y.Z.W), +# which is NOT valid SemVer, so Swift Package Manager ignores them. This derives +# a 3-component tag (X.Y.Z) from the same release that SPM can resolve. +# +# Prerequisites: +# * The root Package.swift (the SPM manifest) must exist at the release tag +# (i.e. this prototype merged to main before the release is cut). +# * Uses the default GITHUB_TOKEN (needs contents: write). No extra secrets. + +on: + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: "4-component release tag to publish for SPM (e.g. v3.10.161.1)" + required: true + type: string + +permissions: + contents: write + +concurrency: + group: spm-release-${{ github.event.release.tag_name || inputs.tag }} + cancel-in-progress: false + +jobs: + spm: + name: Publish SPM xcframework + tag + # Skip drafts/pre-releases; always allow manual dispatch. + if: >- + ${{ github.event_name == 'workflow_dispatch' || + (github.event.release.draft == false && github.event.release.prerelease == false) }} + runs-on: macos-15 # provides Xcode with Apple platform SDKs (xcodebuild, swift) + env: + ARTIFACT: MATTelemetry.xcframework.zip + steps: + - name: Resolve tag and derive SPM version + id: ver + env: + # Pass untrusted tag values through the environment rather than + # interpolating ${{ ... }} into the script body. + RELEASE_TAG: ${{ github.event.release.tag_name }} + INPUT_TAG: ${{ inputs.tag }} + run: | + set -euo pipefail + TAG="${RELEASE_TAG:-$INPUT_TAG}" + if [ -z "$TAG" ]; then echo "::error::No release tag could be resolved."; exit 1; fi + # Only act on 4-component version tags vX.Y.Z.W. + if ! printf '%s' "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'; then + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + echo "::error::Tag '$TAG' is not a 4-component version tag (expected vX.Y.Z.W)." + exit 1 + fi + echo "::notice::Tag '$TAG' is not a 4-component version tag; nothing to publish." + echo "skip=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + VERSION="${TAG#v}" # X.Y.Z.W + SPM_VERSION="${VERSION%.*}" # X.Y.Z (drop the trailing build component) + echo "tag=$TAG" >> "$GITHUB_OUTPUT" + echo "spm_version=$SPM_VERSION" >> "$GITHUB_OUTPUT" + echo "Release $TAG -> SPM tag $SPM_VERSION" + + - name: Checkout the release tag + if: ${{ steps.ver.outputs.skip != 'true' }} + uses: actions/checkout@v4 + with: + ref: ${{ steps.ver.outputs.tag }} + fetch-depth: 0 + # The private lib/modules submodule is intentionally NOT fetched; the + # xcframework ships the core SDK + Obj-C wrappers, matching the vcpkg + # port (the optional modules are excluded there too). + submodules: false + + - name: Build MATTelemetry.xcframework + if: ${{ steps.ver.outputs.skip != 'true' }} + run: | + set -euo pipefail + chmod +x tools/apple/build-xcframework.sh + tools/apple/build-xcframework.sh release + test -f "build/apple/$ARTIFACT" + + - name: Validate SwiftPM package consumption + if: ${{ steps.ver.outputs.skip != 'true' }} + run: | + set -euo pipefail + swift package dump-package > package.json + python3 - <<'PY' + import json + expected = { + "ios": "12.0", + "maccatalyst": "14.0", + "macos": "10.15", + "visionos": "1.0", + } + with open("package.json", encoding="utf-8") as f: + platforms = { + item["platformName"]: item["version"] + for item in json.load(f)["platforms"] + } + if platforms != expected: + raise SystemExit(f"Unexpected Package.swift platforms: {platforms}") + PY + swift build + xcodebuild -scheme OneDSSwift -destination 'generic/platform=iOS Simulator' build + xcodebuild -scheme OneDSSwift -destination 'platform=macOS,variant=Mac Catalyst' build + xcodebuild -scheme OneDSSwift -destination 'generic/platform=visionOS Simulator' build + + - name: Compute SPM checksum + id: sum + if: ${{ steps.ver.outputs.skip != 'true' }} + run: | + set -euo pipefail + checksum="$(swift package compute-checksum "build/apple/$ARTIFACT")" + echo "checksum=$checksum" >> "$GITHUB_OUTPUT" + + - name: Upload xcframework to the release + if: ${{ steps.ver.outputs.skip != 'true' }} + env: + GH_TOKEN: ${{ github.token }} + run: gh release upload "${{ steps.ver.outputs.tag }}" "build/apple/$ARTIFACT" --clobber + + - name: Point Package.swift at the released artifact + if: ${{ steps.ver.outputs.skip != 'true' }} + env: + ASSET_URL: https://github.com/${{ github.repository }}/releases/download/${{ steps.ver.outputs.tag }}/MATTelemetry.xcframework.zip + CHECKSUM: ${{ steps.sum.outputs.checksum }} + run: | + set -euo pipefail + python3 - "$ASSET_URL" "$CHECKSUM" <<'PY' + import re, sys + url, checksum = sys.argv[1], sys.argv[2] + path = "Package.swift" + src = open(path).read() + repl = ( + '.binaryTarget(\n' + ' name: "MATTelemetry",\n' + f' url: "{url}",\n' + f' checksum: "{checksum}")' + ) + out = re.sub( + r'\.binaryTarget\(\s*name:\s*"MATTelemetry",\s*path:\s*"[^"]*"\s*\)', + repl, src, count=1) + assert out != src, "binaryTarget(path:) block not found in Package.swift" + open(path, "w").write(out) + PY + + - name: Commit manifest and push the 3-component SPM tag + if: ${{ steps.ver.outputs.skip != 'true' }} + run: | + set -euo pipefail + if git ls-remote --exit-code --tags origin "refs/tags/${{ steps.ver.outputs.spm_version }}" >/dev/null; then + echo "::notice::SPM tag ${{ steps.ver.outputs.spm_version }} already exists; skipping tag publish." + exit 0 + fi + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add Package.swift tools/apple/MATTelemetryAvailability.json + git commit -m "[spm] ${{ steps.ver.outputs.spm_version }}: pin xcframework url + checksum" + # The SPM tag points at this commit (release source + resolved + # binaryTarget). It is published as a tag only, not merged to a branch. + git tag -a "${{ steps.ver.outputs.spm_version }}" \ + -m "Swift Package Manager release ${{ steps.ver.outputs.spm_version }} (from ${{ steps.ver.outputs.tag }})" + git push origin "refs/tags/${{ steps.ver.outputs.spm_version }}" + echo "Published SPM tag ${{ steps.ver.outputs.spm_version }}" diff --git a/.github/workflows/vcpkg-release-bump.yml b/.github/workflows/vcpkg-release-bump.yml new file mode 100644 index 000000000..d09706242 --- /dev/null +++ b/.github/workflows/vcpkg-release-bump.yml @@ -0,0 +1,193 @@ +name: Vcpkg release bump + +# Opens a version-bump pull request against microsoft/vcpkg for the +# `cpp-client-telemetry` port whenever a new SDK release is published. +# +# It runs ONLY when a new version is cut: +# * automatically on a published, non-draft, non-prerelease GitHub Release +# whose tag looks like a version (vMAJOR.MINOR.PATCH.BUILD), or +# * manually via workflow_dispatch for a specific tag (recovery / re-run). +# It never runs on ordinary pushes, and it opens no PR if the port already +# matches the release (no version change). +# +# One-time setup required in this repository: +# * Variable VCPKG_FORK_REPO -> the vcpkg fork to push branches to, +# e.g. "your-org/vcpkg". +# * Secret VCPKG_BUMP_TOKEN -> a PAT (classic: repo+workflow, or +# fine-grained: Contents+Pull requests RW on +# the fork) able to push to VCPKG_FORK_REPO and +# open pull requests on microsoft/vcpkg. + +on: + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: "Release tag to bump the vcpkg port to (e.g. v3.10.161.1)" + required: true + type: string + +permissions: + contents: read + +concurrency: + group: vcpkg-release-bump-${{ github.event.release.tag_name || github.event.inputs.tag }} + cancel-in-progress: false + +jobs: + bump: + name: Bump cpp-client-telemetry port + # Skip drafts and pre-releases; always allow manual dispatch. + if: >- + ${{ github.event_name == 'workflow_dispatch' || + (github.event.release.draft == false && github.event.release.prerelease == false) }} + runs-on: ubuntu-latest + env: + UPSTREAM_REPO: ${{ github.repository }} # microsoft/cpp_client_telemetry + VCPKG_UPSTREAM: microsoft/vcpkg + VCPKG_FORK_REPO: ${{ vars.VCPKG_FORK_REPO }} + PORT: cpp-client-telemetry + steps: + - name: Validate configuration + env: + VCPKG_BUMP_TOKEN: ${{ secrets.VCPKG_BUMP_TOKEN }} + run: | + set -euo pipefail + if [ -z "${VCPKG_FORK_REPO}" ]; then + echo "::error::Repository variable VCPKG_FORK_REPO is not set (e.g. 'your-org/vcpkg')." + exit 1 + fi + if [ -z "${VCPKG_BUMP_TOKEN}" ]; then + echo "::error::Secret VCPKG_BUMP_TOKEN is not set. Provide a token that can push to ${VCPKG_FORK_REPO} and open PRs on ${VCPKG_UPSTREAM}." + exit 1 + fi + + - name: Resolve tag and version + id: ver + env: + # Pass untrusted tag values through the environment instead of + # interpolating ${{ ... }} directly into the script body, so a tag + # containing shell metacharacters cannot inject commands into this + # step (which shares a runner with later PAT-bearing steps). + RELEASE_TAG: ${{ github.event.release.tag_name }} + INPUT_TAG: ${{ github.event.inputs.tag }} + run: | + set -euo pipefail + TAG="${RELEASE_TAG:-$INPUT_TAG}" + if [ -z "${TAG}" ]; then echo "::error::No release tag could be resolved."; exit 1; fi + # Only act on version tags: vMAJOR.MINOR.PATCH.BUILD. A non-matching + # tag from the automatic release trigger is a clean no-op (the SDK also + # has historical 3-part tags such as v3.3.8); a non-matching tag from a + # manual workflow_dispatch is user error and fails loudly. + if ! printf '%s' "${TAG}" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'; then + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + echo "::error::Tag '${TAG}' is not a version tag (expected vX.Y.Z.W)." + exit 1 + fi + echo "::notice::Tag '${TAG}' is not a version tag (expected vX.Y.Z.W); nothing to bump." + echo "skip=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + VERSION="${TAG#v}" + echo "tag=${TAG}" >> "$GITHUB_OUTPUT" + echo "version=${VERSION}" >> "$GITHUB_OUTPUT" + echo "branch=port/${PORT}-${VERSION}" >> "$GITHUB_OUTPUT" + echo "Bumping ${PORT} -> tag=${TAG} version=${VERSION}" + + - name: Compute source archive SHA512 + id: sha + if: ${{ steps.ver.outputs.skip != 'true' }} + run: | + set -euo pipefail + URL="https://github.com/${UPSTREAM_REPO}/archive/${{ steps.ver.outputs.tag }}.tar.gz" + echo "Downloading ${URL}" + curl -fsSL --retry 3 "${URL}" -o source.tar.gz + SHA512="$(sha512sum source.tar.gz | cut -d' ' -f1)" + echo "sha512=${SHA512}" >> "$GITHUB_OUTPUT" + echo "SHA512=${SHA512}" + + - name: Clone vcpkg fork and branch off upstream master + if: ${{ steps.ver.outputs.skip != 'true' }} + env: + GH_TOKEN: ${{ secrets.VCPKG_BUMP_TOKEN }} + run: | + set -euo pipefail + # Authenticate git via gh's credential helper instead of embedding the + # token in the clone URL (which would persist it in .git/config and + # risk leaking it if git echoes the remote). The helper is written to + # the global gitconfig and reused by the later push step. + gh auth setup-git + git clone --depth 1 "https://github.com/${VCPKG_FORK_REPO}.git" vcpkg + cd vcpkg + git remote add upstream "https://github.com/${VCPKG_UPSTREAM}.git" + git fetch --depth 1 upstream master + git checkout -B "${{ steps.ver.outputs.branch }}" upstream/master + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + + - name: Bootstrap vcpkg + if: ${{ steps.ver.outputs.skip != 'true' }} + run: cd vcpkg && ./bootstrap-vcpkg.sh -disableMetrics + + - name: Update port REF, SHA512 and version + if: ${{ steps.ver.outputs.skip != 'true' }} + run: | + set -euo pipefail + cd vcpkg + PORTFILE="ports/${PORT}/portfile.cmake" + MANIFEST="ports/${PORT}/vcpkg.json" + if [ ! -f "${PORTFILE}" ] || [ ! -f "${MANIFEST}" ]; then + echo "::error::${PORT} port not found in ${VCPKG_UPSTREAM}. The port must already be in the registry before it can be bumped." + exit 1 + fi + sed -i -E "s|^([[:space:]]*REF[[:space:]]+).*$|\1${{ steps.ver.outputs.tag }}|" "${PORTFILE}" + sed -i -E "s|^([[:space:]]*SHA512[[:space:]]+).*$|\1${{ steps.sha.outputs.sha512 }}|" "${PORTFILE}" + jq --arg v "${{ steps.ver.outputs.version }}" '.version = $v | del(."port-version")' "${MANIFEST}" > "${MANIFEST}.tmp" + mv "${MANIFEST}.tmp" "${MANIFEST}" + ./vcpkg format-manifest "${MANIFEST}" + + - name: Detect change + id: diff + if: ${{ steps.ver.outputs.skip != 'true' }} + run: | + set -euo pipefail + cd vcpkg + if git diff --quiet -- "ports/${PORT}"; then + echo "changed=false" >> "$GITHUB_OUTPUT" + echo "No change: ${PORT} is already at ${{ steps.ver.outputs.version }} with this REF/SHA512. Nothing to do." + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + + - name: Commit, update version DB, push and open PR + if: ${{ steps.ver.outputs.skip != 'true' && steps.diff.outputs.changed == 'true' }} + env: + GH_TOKEN: ${{ secrets.VCPKG_BUMP_TOKEN }} + run: | + set -euo pipefail + cd vcpkg + # gh auth setup-git ran in the clone step; reuse that credential helper + # so 'git push' authenticates without a token in the remote URL. + BR="${{ steps.ver.outputs.branch }}" + git add "ports/${PORT}" + git commit -m "[${PORT}] Update to ${{ steps.ver.outputs.version }}" + ./vcpkg x-add-version "${PORT}" --overwrite-version + git add versions + git commit -m "[${PORT}] Update version database" + # Ensure a remote-tracking ref exists so --force-with-lease has a lease + # to compare against on reruns: the bump branch may already exist on the + # fork but be absent from this fresh clone. Ignore failure on the first + # run, when the branch does not exist remotely yet. + git fetch origin "+refs/heads/${BR}:refs/remotes/origin/${BR}" || true + git push --force-with-lease origin "${BR}" + if [ -n "$(gh pr list --repo "${VCPKG_UPSTREAM}" --head "$(printf '%s' "${VCPKG_FORK_REPO}" | cut -d/ -f1):${BR}" --state open --json number --jq '.[0].number // empty' 2>/dev/null)" ]; then + echo "An open PR already exists for ${BR}; the force-pushed branch refreshes it." + else + gh pr create \ + --repo "${VCPKG_UPSTREAM}" \ + --base master \ + --head "$(printf '%s' "${VCPKG_FORK_REPO}" | cut -d/ -f1):${BR}" \ + --title "[${PORT}] Update to ${{ steps.ver.outputs.version }}" \ + --body "Automated port bump to [\`${UPSTREAM_REPO}@${{ steps.ver.outputs.tag }}\`](https://github.com/${UPSTREAM_REPO}/releases/tag/${{ steps.ver.outputs.tag }}). Generated by the \`vcpkg-release-bump\` workflow." + fi diff --git a/CMakeLists.txt b/CMakeLists.txt index 7a0ba0e82..4b8281086 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,30 +54,42 @@ if(APPLE) if(FORCE_RESET_OSX_DEPLOYMENT_TARGET) set(CMAKE_OSX_DEPLOYMENT_TARGET "" CACHE STRING "Force unset of the deployment target for iOS" FORCE) - if (${IOS_PLAT} STREQUAL "iphonesimulator") + if ("${IOS_PLAT}" STREQUAL "iphonesimulator") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mios-simulator-version-min=${IOS_DEPLOYMENT_TARGET}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mios-simulator-version-min=${IOS_DEPLOYMENT_TARGET}") - else() + elseif("${IOS_PLAT}" STREQUAL "iphoneos") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -miphoneos-version-min=${IOS_DEPLOYMENT_TARGET}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -miphoneos-version-min=${IOS_DEPLOYMENT_TARGET}") endif() endif() - if((${IOS_PLAT} STREQUAL "iphoneos") OR (${IOS_PLAT} STREQUAL "iphonesimulator") OR (${IOS_PLAT} STREQUAL "xros") OR (${IOS_PLAT} STREQUAL "xrsimulator")) + if("${IOS_PLAT}" STREQUAL "maccatalyst") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -target ${IOS_ARCH}-apple-ios${IOS_DEPLOYMENT_TARGET}-macabi") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -target ${IOS_ARCH}-apple-ios${IOS_DEPLOYMENT_TARGET}-macabi") + set(IOS_PLATFORM "macosx") + elseif("${IOS_PLAT}" STREQUAL "xros") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -target ${IOS_ARCH}-apple-xros${IOS_DEPLOYMENT_TARGET}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -target ${IOS_ARCH}-apple-xros${IOS_DEPLOYMENT_TARGET}") + set(IOS_PLATFORM "${IOS_PLAT}") + elseif("${IOS_PLAT}" STREQUAL "xrsimulator") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -target ${IOS_ARCH}-apple-xros${IOS_DEPLOYMENT_TARGET}-simulator") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -target ${IOS_ARCH}-apple-xros${IOS_DEPLOYMENT_TARGET}-simulator") + set(IOS_PLATFORM "${IOS_PLAT}") + elseif(("${IOS_PLAT}" STREQUAL "iphoneos") OR ("${IOS_PLAT}" STREQUAL "iphonesimulator")) set(IOS_PLATFORM "${IOS_PLAT}") else() message(FATAL_ERROR "Unrecognized iOS platform '${IOS_PLAT}'") endif() - if(${IOS_ARCH} STREQUAL "x86_64") + if("${IOS_ARCH}" STREQUAL "x86_64") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -arch x86_64") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -arch x86_64") set(CMAKE_SYSTEM_PROCESSOR x86_64) - elseif(${IOS_ARCH} STREQUAL "arm64") + elseif("${IOS_ARCH}" STREQUAL "arm64") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -arch arm64") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -arch arm64") set(CMAKE_SYSTEM_PROCESSOR arm64) - elseif(${IOS_ARCH} STREQUAL "arm64e") + elseif("${IOS_ARCH}" STREQUAL "arm64e") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -arch arm64e") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -arch arm64e") set(CMAKE_SYSTEM_PROCESSOR arm64e) @@ -89,6 +101,11 @@ if(APPLE) OUTPUT_VARIABLE CMAKE_OSX_SYSROOT ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) + if("${IOS_PLAT}" STREQUAL "maccatalyst") + set(IOS_SUPPORT_FRAMEWORKS "${CMAKE_OSX_SYSROOT}/System/iOSSupport/System/Library/Frameworks") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -iframework ${IOS_SUPPORT_FRAMEWORKS}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -iframework ${IOS_SUPPORT_FRAMEWORKS}") + endif() message(STATUS "CMAKE_OSX_SYSROOT ${CMAKE_OSX_SYSROOT}") message(STATUS "ARCHITECTURE: ${CMAKE_SYSTEM_PROCESSOR}") message(STATUS "PLATFORM: ${IOS_PLATFORM}") @@ -149,16 +166,17 @@ else() endif() if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - # Using GCC with -s and -Wl linker flags - set(REL_FLAGS "-s -Wl,--gc-sections -Os ${WARN_FLAGS} -ffunction-sections -fdata-sections -fmerge-all-constants") + # Using GCC with -s and -Wl linker flags. -ffunction-sections/-fdata-sections + # are set once for all dep modes by the global block further below. + set(REL_FLAGS "-s -Wl,--gc-sections -Os ${WARN_FLAGS} -fmerge-all-constants") elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") set(REL_FLAGS "${WARN_FLAGS}") elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") - # AppleClang does not support -ffunction-sections and -fdata-sections with the -fembed-bitcode and -fembed-bitcode-marker set(REL_FLAGS "-Os ${WARN_FLAGS} -fmerge-all-constants") else() - # Using clang - strip unsupported GCC options - set(REL_FLAGS "-Os ${WARN_FLAGS} -ffunction-sections -fmerge-all-constants") + # Using clang - strip unsupported GCC options (-ffunction-sections is set by + # the global block further below). + set(REL_FLAGS "-Os ${WARN_FLAGS} -fmerge-all-constants") endif() ## Uncomment this to reduce the volume of note warnings on RPi4 w/gcc-8 Ref. https://gcc.gnu.org/ml/gcc/2017-05/msg00073.html @@ -206,6 +224,55 @@ endif() endif() # NOT MATSDK_USE_VCPKG_DEPS (compiler flags) +# --- Dead-strip enablement (applies in BOTH vendored and vcpkg modes) --------- +# Deliberate exception to the "let the toolchain manage compiler flags" note +# above (the NOT MATSDK_USE_VCPKG_DEPS block): these flags are NOT optimization +# or dependency choices the vcpkg toolchain owns -- they only split functions and +# data into separate COMDATs/sections so a *consumer's* linker can drop +# unreferenced SDK code (MSVC /OPT:REF + /OPT:ICF, GNU/Clang --gc-sections, Apple +# ld -dead_strip). The toolchain does not set them, and the vcpkg-packaged +# library (and every MSVC build, which never gets /Gy from the block above) would +# otherwise link whole .obj files instead of individual functions. Applying them +# here in both modes closes that gap and matches the MSBuild Release projects, +# which already enable FunctionLevelLinking + OptimizeReferences + COMDATFolding. +if(MSVC) + # /Gy (function-level linking) is supported by both cl.exe and clang-cl. + add_compile_options(/Gy) + # /Gw (whole-program global data) is cl.exe-only; the ClangCL toolset (for + # which MSVC is also true) does not support it. + if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + add_compile_options(/Gw) + endif() +elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") + # On Mach-O, clang emits .subsections_via_symbols, so ld64's -dead_strip + # already removes unreferenced code at per-symbol (function) granularity + # without -ffunction-sections; we add it only for cross-toolchain + # consistency. -fdata-sections is omitted because it historically conflicted + # with bitcode on AppleClang. + add_compile_options(-ffunction-sections) +else() + # GCC / Clang (Linux, Android, MinGW) + add_compile_options(-ffunction-sections -fdata-sections) +endif() + +# Hidden symbol visibility (non-Windows): export only the MATSDK_LIBABI-decorated +# public API (classes + the C API), hiding SDK internals and the bundled +# sqlite3/zlib. This shrinks the dynamic symbol table (faster dynamic +# linking/loading, smaller binaries) and enables more inlining + dead-code +# elimination -- the non-Windows analog of what /Gy plus the consumer's /OPT:REF +# achieve on MSVC. All Windows toolchains (MSVC, MinGW, ClangCL) restrict exports +# via __declspec(dllexport) on MATSDK_LIBABI (lib/include/public/ctmacros.hpp), +# so this is gated on NOT WIN32 (not NOT MSVC, which would also catch MinGW/ +# Clang-GNU Windows builds and apply ELF-style visibility that does not belong on +# a PE/COFF target). +if(NOT WIN32) + # -fvisibility=hidden applies to C and C++; -fvisibility-inlines-hidden is a + # C++-only option, so scope it to CXX. (Applying it to C sources -- e.g. the + # bundled sqlite3/zlib on the legacy Android path -- makes Clang emit an + # "unused argument" warning that becomes an error under the project's -Werror.) + add_compile_options(-fvisibility=hidden $<$:-fvisibility-inlines-hidden>) +endif() + include(tools/Utils.cmake) include(GNUInstallDirs) include(CMakePackageConfigHelpers) diff --git a/Package.swift b/Package.swift new file mode 100644 index 000000000..18af3547c --- /dev/null +++ b/Package.swift @@ -0,0 +1,129 @@ +// swift-tools-version: 5.9 +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Swift Package Manager manifest for the 1DS C++ SDK (Microsoft Applications +// Telemetry) on Apple platforms. +// +// PROTOTYPE — distribution model: +// * The compiled C++ core + Obj-C wrappers ship as a prebuilt binary +// xcframework (built by tools/apple/build-xcframework.sh). This avoids +// compiling the CMake/Bond/sqlite/zlib C++ tree through SPM, which is not +// practical. +// * The thin Swift wrapper (wrappers/swift/Sources/OneDSSwift) is compiled +// from source on top of the Obj-C module vended by the xcframework. +// +// Local development: +// 1. Run `tools/apple/build-xcframework.sh release` on macOS with Xcode. +// It produces ./build/apple/MATTelemetry.xcframework. +// 2. `swift build` validates macOS consumption; for iOS / Mac Catalyst / +// visionOS, add this package as a local dependency or build the package +// with the desired Xcode destination. +// +// Release distribution (so consumers can add the repo by URL in Xcode): +// .github/workflows/spm-release.yml builds and uploads the xcframework, +// computes the checksum, rewrites the local `.binaryTarget(... path:)` below +// to `url:`+`checksum:`, and pushes the 3-component SemVer tag that SPM can +// resolve. + +import PackageDescription +import Foundation + +let packageDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + +func readAvailability() -> [String: Bool] { + let candidates = [ + "build/apple/MATTelemetryAvailability.json", + "tools/apple/MATTelemetryAvailability.json", + ] + + for relativePath in candidates { + let url = packageDirectory.appendingPathComponent(relativePath).standardizedFileURL + guard let data = try? Data(contentsOf: url), + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Bool] else { + continue + } + return object + } + + return [:] +} + +let availability = readAvailability() +let hasDiagnosticDataViewer = availability["diagnosticDataViewer"] ?? false +let hasPrivacyGuard = availability["privacyGuard"] ?? false +let hasSanitizer = availability["sanitizer"] ?? false + +var excludedSources: [String] = [] +var swiftSettings: [SwiftSetting] = [] + +if !hasDiagnosticDataViewer { + excludedSources.append("DiagnosticDataViewer.swift") +} + +if hasPrivacyGuard { + swiftSettings.append(.define("MATSDK_PRIVACYGUARD_AVAILABLE")) +} else { + excludedSources.append(contentsOf: [ + "PrivacyGuard.swift", + "PrivacyGuardInitConfig.swift", + ]) +} + +if !hasSanitizer { + excludedSources.append(contentsOf: [ + "Sanitizer.swift", + "SanitizerInitConfig.swift", + ]) +} + +let package = Package( + name: "OneDSSwift", + platforms: [ + .iOS(.v12), + .macCatalyst(.v14), + .macOS(.v10_15), + .visionOS(.v1), + ], + products: [ + .library(name: "OneDSSwift", targets: ["OneDSSwift"]), + ], + targets: [ + // Prebuilt C++ core + Obj-C wrappers. The xcframework's bundled + // module map vends the Clang module `MATTelemetryObjC` (see + // tools/apple/module.modulemap), which the Swift layer imports. + // + // For a tagged release, swap the local path for the hosted artifact: + // + // .binaryTarget( + // name: "MATTelemetry", + // url: "https://github.com/microsoft/cpp_client_telemetry/releases/download/v3.10.161.1/MATTelemetry.xcframework.zip", + // checksum: ""), + .binaryTarget( + name: "MATTelemetry", + path: "build/apple/MATTelemetry.xcframework"), + + // Thin Swift API layer (source). Depends on the Obj-C module from the + // xcframework. The conditional source exclusions above must stay in sync + // with the headers baked into the xcframework. + .target( + name: "OneDSSwift", + dependencies: ["MATTelemetry"], + path: "wrappers/swift/Sources/OneDSSwift", + exclude: excludedSources, + swiftSettings: swiftSettings, + linkerSettings: [ + .linkedLibrary("c++"), + .linkedLibrary("sqlite3"), + .linkedLibrary("z"), + .linkedFramework("CFNetwork", .when(platforms: [.iOS, .macCatalyst, .macOS, .visionOS])), + .linkedFramework("CoreFoundation", .when(platforms: [.iOS, .macCatalyst, .macOS, .visionOS])), + .linkedFramework("Foundation", .when(platforms: [.iOS, .macCatalyst, .macOS, .visionOS])), + .linkedFramework("Network", .when(platforms: [.iOS, .macCatalyst, .macOS, .visionOS])), + .linkedFramework("SystemConfiguration", .when(platforms: [.iOS, .macCatalyst, .macOS, .visionOS])), + .linkedFramework("IOKit", .when(platforms: [.macOS])), + .linkedFramework("UIKit", .when(platforms: [.iOS, .macCatalyst, .visionOS])), + ]), + ] +) diff --git a/build-ios.sh b/build-ios.sh index d316fe2fa..d96b93bc4 100755 --- a/build-ios.sh +++ b/build-ios.sh @@ -4,7 +4,7 @@ # build-ios.sh [clean] [release|debug] ${ARCH} ${PLATFORM} # where # ARCH = arm64|arm64e|x86_64 -# PLATFORM = iphoneos|iphonesimulator|xros|xrsimulator +# PLATFORM = iphoneos|iphonesimulator|maccatalyst|xros|xrsimulator if [ "$1" == "clean" ]; then echo "build-ios.sh: cleaning previous build artifacts" @@ -37,7 +37,7 @@ elif [ "$1" == "x86_64" ]; then shift fi -# the last param is expected to specify the platform name: iphoneos|iphonesimulator|xros|xrsimulator +# the last param is expected to specify the platform name: iphoneos|iphonesimulator|maccatalyst|xros|xrsimulator # so if it is non-empty and it is not "device", we take it as a valid platform name # otherwise we fall back to old iOS logic which only supported iphoneos|iphonesimulator IOS_PLAT="iphonesimulator" @@ -54,18 +54,31 @@ DEPLOYMENT_TARGET="" if [ "$IOS_PLAT" == "iphoneos" ] || [ "$IOS_PLAT" == "iphonesimulator" ]; then SYS_NAME="iOS" + IOS_SYSROOT="$IOS_PLAT" DEPLOYMENT_TARGET="$IOS_DEPLOYMENT_TARGET" if [ -z "$DEPLOYMENT_TARGET" ]; then DEPLOYMENT_TARGET="12.0" FORCE_RESET_DEPLOYMENT_TARGET=YES fi +elif [ "$IOS_PLAT" == "maccatalyst" ]; then + SYS_NAME="iOS" + IOS_SYSROOT="macosx" + DEPLOYMENT_TARGET="$MACCATALYST_DEPLOYMENT_TARGET" + if [ -z "$DEPLOYMENT_TARGET" ]; then + DEPLOYMENT_TARGET="14.0" + FORCE_RESET_DEPLOYMENT_TARGET=YES + fi elif [ "$IOS_PLAT" == "xros" ] || [ "$IOS_PLAT" == "xrsimulator" ]; then SYS_NAME="visionOS" + IOS_SYSROOT="$IOS_PLAT" DEPLOYMENT_TARGET="$XROS_DEPLOYMENT_TARGET" if [ -z "$DEPLOYMENT_TARGET" ]; then DEPLOYMENT_TARGET="1.0" FORCE_RESET_DEPLOYMENT_TARGET=YES fi +else + echo "ERROR: unsupported Apple platform '$IOS_PLAT'. Expected iphoneos, iphonesimulator, maccatalyst, xros, or xrsimulator." 1>&2 + exit 1 fi echo "deployment target = $DEPLOYMENT_TARGET" @@ -92,10 +105,14 @@ cd out CMAKE_PACKAGE_TYPE=tgz -cmake_cmd="cmake -DCMAKE_OSX_SYSROOT=$IOS_PLAT -DCMAKE_SYSTEM_NAME=$SYS_NAME -DCMAKE_IOS_ARCH_ABI=$IOS_ARCH -DCMAKE_OSX_DEPLOYMENT_TARGET=$DEPLOYMENT_TARGET -DBUILD_IOS=YES -DIOS_ARCH=$IOS_ARCH -DIOS_PLAT=$IOS_PLAT -DIOS_DEPLOYMENT_TARGET=$DEPLOYMENT_TARGET -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_PACKAGE_TYPE=$CMAKE_PACKAGE_TYPE -DFORCE_RESET_DEPLOYMENT_TARGET=$FORCE_RESET_DEPLOYMENT_TARGET $CMAKE_OPTS .." +cmake_cmd="cmake -DCMAKE_OSX_SYSROOT=$IOS_SYSROOT -DCMAKE_SYSTEM_NAME=$SYS_NAME -DCMAKE_IOS_ARCH_ABI=$IOS_ARCH -DCMAKE_OSX_DEPLOYMENT_TARGET=$DEPLOYMENT_TARGET -DBUILD_IOS=YES -DIOS_ARCH=$IOS_ARCH -DIOS_PLAT=$IOS_PLAT -DIOS_DEPLOYMENT_TARGET=$DEPLOYMENT_TARGET -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_PACKAGE_TYPE=$CMAKE_PACKAGE_TYPE -DFORCE_RESET_DEPLOYMENT_TARGET=$FORCE_RESET_DEPLOYMENT_TARGET $CMAKE_OPTS .." echo "${cmake_cmd}" eval $cmake_cmd make -make package +if [ "${MATTELEMETRY_SKIP_PACKAGE:-}" = "1" ]; then + echo "MATTELEMETRY_SKIP_PACKAGE=1: skipping package creation" +else + make package +fi diff --git a/docs/building-with-vcpkg.md b/docs/building-with-vcpkg.md index b736ba3c5..7e5cff7d0 100644 --- a/docs/building-with-vcpkg.md +++ b/docs/building-with-vcpkg.md @@ -1,6 +1,6 @@ # Building 1DS C++ SDK with vcpkg -[vcpkg](https://vcpkg.io/) is a Microsoft cross-platform open source C++ package manager. Onboarding instructions for Windows, Linux and Mac OS X [available here](https://docs.microsoft.com/en-us/cpp/build/vcpkg). This document assumes that the customer build system is already configured to use vcpkg ([getting started guide](https://learn.microsoft.com/en-us/vcpkg/get_started/overview)). 1DS C++ SDK maintainers provide a build recipe, `cpp-client-telemetry` port or CONTROL file for vcpkg. The mainline vcpkg repo is refreshed to point to latest stable open source release of 1DS C++ SDK. +[vcpkg](https://vcpkg.io/) is a Microsoft cross-platform open source C++ package manager. Onboarding instructions for Windows, Linux and Mac OS X [available here](https://docs.microsoft.com/en-us/cpp/build/vcpkg). This document assumes that the customer build system is already configured to use vcpkg ([getting started guide](https://learn.microsoft.com/en-us/vcpkg/get_started/overview)). The `cpp-client-telemetry` port is published in the official vcpkg registry, so it can be consumed directly with no overlay or extra configuration. Maintainers refresh the registry to point to the latest stable open source release of the 1DS C++ SDK on each release. The port provides the core SDK — the `MSTelemetry::mat` target and its public C++ headers. The optional Microsoft-proprietary modules (Privacy Guard, @@ -16,7 +16,8 @@ git clone --recurse-submodules https://github.com/microsoft/cpp_client_telemetry ### Installing from the vcpkg registry -Once a new port has been accepted into the official vcpkg registry, install with: +The `cpp-client-telemetry` port is available in the [official vcpkg registry](https://github.com/microsoft/vcpkg/tree/master/ports/cpp-client-telemetry), +so you can install it directly — no overlay or extra configuration required: ```console vcpkg install cpp-client-telemetry @@ -26,8 +27,9 @@ That's it! The package should be compiled for the current OS. ### Installing from the overlay port (development / pre-release) -Before the port is published, or to test local changes, use the overlay port -shipped in this repository: +The overlay port shipped in this repository is for **development only** — use it +to test local changes to the port, or a newer SDK revision, before they are +published to the registry: ```console git clone https://github.com/microsoft/cpp_client_telemetry @@ -190,6 +192,70 @@ will automatically use the optimized zlib-ng build. > zlib. When using `ZLIB_COMPAT=ON`, ensure all dependencies resolve to > zlib-ng rather than mixing stock zlib and zlib-ng. +## Reducing binary footprint + +This section applies when the SDK is linked **statically** into your binary +(the default for the `*-static` vcpkg triplets) — most footprint control then +lives on *your* side of the link. If you instead consume a **dynamic** `mat` +(e.g. the default `x64-windows` triplet, or `BUILD_SHARED_LIBS=ON`), the runtime +ships as its own `mat.dll` / `libmat.so` / `libmat.dylib`; the SDK's own +`-fvisibility=hidden` and `/Gy /Gw` already trim its exported symbol table, and +the consumer-side linker options below are specific to the static-link case. + +### Enable linker dead-stripping (largest lever) + +The SDK is compiled with function-level linking (`/Gy /Gw` on MSVC, +`-ffunction-sections -fdata-sections` on GCC/Clang) so that **your** linker can +discard SDK code you never reference. Make sure your final link enables it: + +- **MSVC:** `/OPT:REF` (drop unreferenced functions/data) and `/OPT:ICF` (fold + identical COMDATs). These are on by default for Release, **but `/DEBUG` flips + their default to off** (`/OPT:NOREF,NOICF`, per the MSVC `/OPT` docs) — so if + you ship PDBs, re-enable them explicitly. `/OPT:REF` is also incompatible with + incremental linking, so set `/INCREMENTAL:NO`: + + ```cmake + target_link_options(your_target PRIVATE + $<$,$>:/OPT:REF> + $<$,$>:/OPT:ICF> + $<$,$>:/INCREMENTAL:NO>) + ``` + +- **GCC / Clang:** link with `-Wl,--gc-sections`. +- **Apple (clang):** link with `-Wl,-dead_strip`. + +This is by far the largest lever — on a static `x64-windows-static` Release link +it can roughly halve the binary. The SDK's `/Gy /Gw` flags only *enable* this; +the stripping happens at your link. Keep the SDK a static dependency linked +*into* your binary: if you re-export its API across your own DLL boundary, the +export table pins its symbols and defeats `/OPT:REF`. + +### Drop unused SQLite features (json1) + +The SDK uses SQLite only for offline event storage — plain tables and indexes, +with no JSON, FTS, R*Tree, or virtual-table features. This in-repo overlay port +already requests `sqlite3` with `default-features: false` on its dependency edge +(the published registry port will follow once this change is upstreamed). + +vcpkg unions feature requests across the whole dependency graph, and a +transitive opt-out alone is **not** enough: you must **also** request `sqlite3` +with `default-features: false` in your own top-level manifest to actually omit +`json1` (which compiles SQLite with `SQLITE_OMIT_JSON`, ~50 KB smaller on a +static `x64-windows-static` Release build): + +```json +{ + "dependencies": [ + "cpp-client-telemetry", + { "name": "sqlite3", "default-features": false } + ] +} +``` + +If any package in your build (or your own code) needs SQLite's JSON functions, +request `sqlite3[json1]` instead and the extension is restored for the whole +graph. + ## How It Works: MATSDK_USE_VCPKG_DEPS When the SDK detects it is being built via vcpkg (by checking for diff --git a/docs/cpp-start-android.md b/docs/cpp-start-android.md index 0f979bcda..2281a5e31 100644 --- a/docs/cpp-start-android.md +++ b/docs/cpp-start-android.md @@ -14,6 +14,8 @@ The Gradle wrapper in ```android_build``` builds two modules, ```app``` and ```m On Android, there are two database implementations to choose from. By default (the main branch on Github), the SDK will use the Android-supported androidx.Room database package. This reduces APK size because we don't need to compile and link in a copy of SQLite in native code (SQLite is hundreds of kB per ABI of APK file size). Room does have a slight CPU performance disadvantage since database transactions cross the JNI boundary when native code uses it. If you wish to change from Room to the native SQLite implementation, you should change the two module ```build.gradle``` files (app and maesdk). In those files, you will see an argument to CMake to select Room: ```"-DUSE_ROOM=1"```. Change this to ```"-DUSE_ROOM=0``` to select the native SQLite. +When using the Room implementation, the ```maesdk``` AAR brings ```androidx.room``` as a transitive dependency, pinned in ```lib/android_build/maesdk/build.gradle``` (currently ```2.8.4```). The SDK's native (JNI) code is compiled and tested against this version and the Room-generated schema. Because Gradle resolves a single ```androidx.room``` version for the entire app, if your app (or one of its dependencies) selects a different version, the SDK's native code runs against it. **Do not force ```androidx.room``` below the version the SDK is built against**, and prefer aligning your app on the bundled version (or a compatible newer one). A significantly different Room version can change the shape of query results that cross the JNI boundary and has historically caused native crashes in record retrieval (issue #1227); the SDK now guards against null results defensively, but version alignment avoids subtle behavior differences. + The Room database implementation adds one additional initialization requirement, since it needs a pointer to the JVM and an object reference to the application context. See below (4.5) for the required call to either ```connectContext``` (in Java) or ```ConnectJVM``` (in C++) to set this up. If you are building on Windows, this helper script [build-android.cmd](../build-android.cmd) is provided to illustrate how to deploy the necessary SDK and NDK dependencies. Once you installed the necessary dependencies, you may use Android Studio IDE for local builds. See [ide.cmd](../lib/android_build/ide.cmd) that shows how to build the project from IDE. The `app` project (`maesdktest`) allows to build and run all SDK tests on either emulator or real Android device. While the tests are running, you can monitor the test results in logcat output. diff --git a/docs/sharing-a-single-sdk-runtime.md b/docs/sharing-a-single-sdk-runtime.md new file mode 100644 index 000000000..10e69746d --- /dev/null +++ b/docs/sharing-a-single-sdk-runtime.md @@ -0,0 +1,164 @@ +# Sharing one SDK runtime across several modules in a process + +When more than one module in a single process links this SDK — for example an +application that loads several plug-ins or libraries, each of which uses 1DS — +the easy default (every module statically embeds the SDK) has two costs: + +1. **Size.** The SDK (plus its bundled SQLite/zlib) is duplicated once per module. +2. **Duplicated global state.** Each static copy has its *own* default + `LogManager`, HTTP transport, offline SQLite cache, and upload threads. They do + not share a pipeline, and multiple writers to the same offline-cache path will + corrupt it. + +This document describes how to ship **one** shared SDK runtime (`mat.dll` / +`libmat.so` / `libmat.dylib`) that every module imports, so there is a single +copy on disk and a single set of process-global state. + +There are two ways to consume the shared runtime. **The C API is strongly +recommended** because it removes the fragile C++/CRT ABI coupling between modules. + +--- + +## Option 1 (recommended): consume the stable C API + +The SDK ships a flat **C ABI** in [`mat.h`](../lib/include/public/mat.h). Every +`evt_*` entry point (`evt_open`, `evt_log`, `evt_flush`, `evt_upload`, +`evt_pause`, `evt_resume`, `evt_close`, `evt_configure`, …) is a `static inline` +wrapper that marshals its arguments into a POD struct and calls through a single +exported `__cdecl` symbol, `evt_api_call_default`. + +Consequences that make this the robust choice: + +* **Only one symbol crosses the module boundary, and no C++/STL type does.** The + request is a plain C struct, so there is *no* requirement that the modules and + the shared runtime agree on the C++ standard library ABI (`/MD`, + `_ITERATOR_DEBUG_LEVEL`, MSVC toolset/STL version, libstdc++ vs libc++, + `_GLIBCXX_USE_CXX11_ABI`, …). A 1DS version bump does not force every module to + rebuild in lockstep against an identical toolchain. +* **It does not *require* `__declspec(dllimport)` to link.** A plain C function + resolves through the shared library's import lib even without `dllimport`, so + the C API works across the boundary regardless. Consumers that link the shared + `MSTelemetry::mat` target do get `dllimport` applied automatically (via the + `MATSDK_IMPORT_LIB` interface define this PR adds); for a C function that is a + harmless calling-convention optimization, not a requirement. + +Each module includes `mat.h`, links the one shared runtime, and uses its own +tenant/source. You still pin the **same SDK version** in every module (so the +request/struct layout matches), but you avoid the C++ ABI lockstep entirely. + +## Option 2: consume the C++ API from a shared library + +All modules `find_package(MSTelemetry CONFIG REQUIRED)` and link +`MSTelemetry::mat` (resolving to the import lib); none statically embed the SDK. + +The C++ public API passes C++ standard-library types (`std::string`, `std::map`, +…) across the module boundary, so **every module and the shared runtime must +share one C++ ABI**. If they do not, you get heap corruption / undefined +behavior. Pin all of the following identically: + +| Axis | Requirement | +|------|-------------| +| **CRT linkage (Windows)** | Dynamic CRT (`/MD`, `/MDd` for Debug) everywhere — never `/MT`, and never mix Debug/Release CRT across the boundary. (vcpkg: `VCPKG_CRT_LINKAGE dynamic`.) | +| **STL / iterator debug** | One compiler + STL, one build config. `_ITERATOR_DEBUG_LEVEL` must match (Release `0` vs Debug `2`) — a Release consumer + Debug runtime is a silent layout mismatch. | +| **Toolset** | One MSVC toolset across all binaries (the v14x toolsets share an STL ABI, but don't mix major versions); or one libstdc++/libc++ with the same `_GLIBCXX_USE_CXX11_ABI`. | +| **Language / model** | Same `/std:c++NN`, same `/EHsc` exception model, same architecture, no overridden struct packing. | +| **SDK build options** | Same SDK feature/version selection in every module's manifest — different features mean different headers, hence a different ABI even at the same version. | + +Because the C++ ABI must match exactly across separately built and separately +versioned modules, this option is materially more brittle than the C API. Prefer +Option 1 unless you specifically need the C++ surface and control all modules' +toolchains. + +--- + +## Building the shared runtime with vcpkg (per-port linkage) + +A common requirement is "share *this* SDK, but keep everything else statically +linked (no DLL forest)". Override the library linkage **per port** in your +triplet so only this SDK goes dynamic: + +```cmake +set(VCPKG_CRT_LINKAGE dynamic) +if(PORT STREQUAL "cpp-client-telemetry") + set(VCPKG_LIBRARY_LINKAGE dynamic) # mat.dll / libmat.so / libmat.dylib + import lib +else() + set(VCPKG_LIBRARY_LINKAGE static) +endif() +``` + +The port honors `VCPKG_LIBRARY_LINKAGE` / `BUILD_SHARED_LIBS` and emits the +shared `mat` plus its import lib and the `MSTelemetry` CMake config package. + +### Pin one version across all modules + +All modules must compile against identical SDK headers. Pin the same +`cpp-client-telemetry` version and `builtin-baseline` (or a shared version +override) in every module's manifest, and ideally build all artifacts in the same +CI job/container with the same toolchain image. Most ABI drift comes from +separate modules quietly building on different agents. + +--- + +## How the SDK decorates its public symbols + +The SDK has no `.def` file; on Windows, exporting/importing is driven entirely by +`MATSDK_LIBABI` in [`ctmacros.hpp`](../lib/include/public/ctmacros.hpp), which the +build ties to the actual linkage: + +* **Shared build:** the SDK is compiled with `MATSDK_SHARED_LIB` + (`__declspec(dllexport)`), and the installed `MSTelemetry::mat` target carries + an `INTERFACE` definition of `MATSDK_IMPORT_LIB`, so consumers that + `find_package` + link automatically get `__declspec(dllimport)` — no + consumer-side configuration required. +* **Static build:** nothing is decorated, so the SDK's public symbols are not + re-exported by a consumer DLL that absorbs the static lib. + +On non-Windows platforms the SDK is built with `-fvisibility=hidden` and the +public API is marked `__attribute__((visibility("default")))`, so only the public +API (including the C API) is exported from the shared object. + +--- + +## Coordinate the single runtime's lifetime + +One shared runtime means **one** set of process-global state. Decide ownership: + +* **Recommended — single owner.** The top-level module initializes and tears down + the SDK (`LogManager::Initialize` / `FlushAndTeardown`, or `evt_open` / + `evt_close`). Other modules obtain loggers (their own tenant/source) but never + initialize or tear down. This avoids teardown-ordering crashes. +* **Alternative — named instances.** `LogManagerProvider::CreateLogManager(id)` + gives each module its own instance/tenant/config sharing the one transport; then + you need a last-one-out teardown refcount and **distinct offline-cache paths** + (one shared path with multiple writers corrupts it). +* Teardown must happen exactly once, **last**, after every module has stopped + logging. + +--- + +## Ship exactly one copy on the loader path + +Place a single runtime where every module finds it: + +* **Windows:** the same directory as the consumers (or side-by-side assembly). +* **Linux:** `RPATH=$ORIGIN` so every module resolves the one copy. +* **macOS:** a stable install name, `@rpath/libmat.dylib`. + +Make exactly one package own and ship the SDK runtime; the others declare a +dependency rather than bundling their own. If several packages each ship their +own copy, which one loads is path-order luck — and if their versions differ, you +are back to an ABI mismatch even with "one" DLL. + +--- + +## Validate + +* **Dependency present, definitions absent.** `dumpbin /dependents` (Windows), + `ldd` (Linux), `otool -L` (macOS) on each consumer should show a dependency on + the one `mat` module; `dumpbin /exports` (or `nm -D`) on a consumer should show + it imports — not defines — the SDK symbols. +* **One copy at runtime.** Process Explorer / `/proc//maps` / `vmmap` should + map the `mat` module exactly once; there should be one offline-cache file. +* **(C++ option) CRT/STL smoke test.** Have a consumer pass a `std::string` event + property into the SDK and read it back. A `/MD` vs `/MT` or `_ITERATOR_DEBUG_LEVEL` + mismatch typically crashes immediately (especially in Debug). diff --git a/examples/swift/README.md b/examples/swift/README.md index 2c7db6c3a..3f66816da 100644 --- a/examples/swift/README.md +++ b/examples/swift/README.md @@ -30,7 +30,7 @@ Details: - OneDSSwift: Package containing swift wrappers - Modules Included - - ObjCModule: Module exposing ObjC headers via module.modulemap file. + - MATTelemetryObjC: Module exposing ObjC headers via module.modulemap file. - Libraries and Frameworks to link to Target - [Same as mentioned in the SampleXcodeApp section](#to-be-linked) \ No newline at end of file diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 584c678ec..0d4161811 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -216,7 +216,7 @@ if(PAL_IMPLEMENTATION STREQUAL "CPP11") endif() if(APPLE AND BUILD_OBJC_WRAPPER) message(STATUS "Include ObjC Wrappers") - list(APPEND SRCS + set(OBJC_WRAPPER_SRCS ../wrappers/obj-c/ODWLogger.mm ../wrappers/obj-c/ODWLogManager.mm ../wrappers/obj-c/ODWEventProperties.mm @@ -227,22 +227,23 @@ if(PAL_IMPLEMENTATION STREQUAL "CPP11") ../wrappers/obj-c/ODWSanitizerInitConfig.mm ) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/modules/dataviewer/") - list(APPEND SRCS + list(APPEND OBJC_WRAPPER_SRCS ../wrappers/obj-c/ODWDiagnosticDataViewer.mm ) endif() if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/modules/privacyguard/" AND BUILD_PRIVACYGUARD) set(MATSDK_OBJC_PRIVACYGUARD_AVAILABLE ON) - list(APPEND SRCS + list(APPEND OBJC_WRAPPER_SRCS ../wrappers/obj-c/ODWPrivacyGuard.mm ) endif() if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/modules/sanitizer/" AND BUILD_SANITIZER) set(MATSDK_OBJC_SANITIZER_AVAILABLE ON) - list(APPEND SRCS + list(APPEND OBJC_WRAPPER_SRCS ../wrappers/obj-c/ODWSanitizer.mm ) endif() + list(APPEND SRCS ${OBJC_WRAPPER_SRCS}) endif() if(APPLE AND BUILD_SWIFT_WRAPPER) @@ -271,7 +272,7 @@ elseif(PAL_IMPLEMENTATION STREQUAL "WIN32") if(NOT MATSDK_USE_VCPKG_DEPS) include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/../zlib ${CMAKE_CURRENT_SOURCE_DIR}/../sqlite) endif() -add_definitions(-D_UNICODE -DUNICODE -DWIN32 -DMATSDK_PLATFORM_WINDOWS=1 -DMATSDK_SHARED_LIB=1 -D_UTC_SDK -DUSE_BOND -D_WINDOWS -D_USRDLL -DWINVER=_WIN32_WINNT_WIN7) +add_definitions(-D_UNICODE -DUNICODE -DWIN32 -DMATSDK_PLATFORM_WINDOWS=1 -D_UTC_SDK -DUSE_BOND -D_WINDOWS -D_USRDLL -DWINVER=_WIN32_WINNT_WIN7) remove_definitions(-D_MBCS) list(APPEND SRCS http/HttpClient_WinInet.cpp @@ -323,6 +324,29 @@ else() add_library(mat STATIC ${SRCS}) endif() +# Public-API export decoration (MATSDK_LIBABI in lib/include/public/ctmacros.hpp). +# The SDK has no .def file, so __declspec(dllexport)/(dllimport) on Windows and +# __attribute__((visibility("default"))) elsewhere are the sole export mechanisms, +# and the decoration must follow the actual linkage: +# * shared: the SDK's own translation units export the public API +# (MATSDK_SHARED_LIB, PRIVATE). On Windows, consumers must additionally import +# it -- the INTERFACE MATSDK_IMPORT_LIB is carried by the installed +# MSTelemetry::mat target, so find_package() + link gives consumers dllimport +# automatically with no consumer-side configuration. Non-Windows consumers need +# nothing: they call symbols exported by libmat.so/.dylib. +# * static: decorate nothing, so the SDK's public symbols are NOT re-exported by +# a consumer DLL/.so that statically absorbs this library. Windows needs an +# explicit (empty) MATSDK_STATIC_LIB; elsewhere the empty MATSDK_LIBABI default +# plus -fvisibility=hidden (root CMakeLists.txt) already hides them. +if(BUILD_SHARED_LIBS) + target_compile_definitions(mat PRIVATE MATSDK_SHARED_LIB=1) + if(WIN32) + target_compile_definitions(mat INTERFACE MATSDK_IMPORT_LIB=1) + endif() +elseif(WIN32) + target_compile_definitions(mat PUBLIC MATSDK_STATIC_LIB=1) +endif() + # Target-based include paths for vcpkg / install workflow. # PUBLIC propagates to consumers; PRIVATE is SDK-internal only. # BUILD_INTERFACE is used during the SDK build; INSTALL_INTERFACE is used @@ -339,6 +363,17 @@ target_include_directories(mat ) if(APPLE AND BUILD_OBJC_WRAPPER) + if(BUILD_SHARED_LIBS AND OBJC_WRAPPER_SRCS) + # The root CMakeLists.txt applies -fvisibility=hidden globally to shrink the + # exported symbol table of the core C++ SDK. For Objective-C that also hides + # the wrapper class symbols (_OBJC_CLASS_$_ODW*), which are public API on + # Apple: a shared libmat.dylib would export no ODW* classes and consumers + # would fail to link (undefined _OBJC_CLASS_$_...). Re-export just the wrapper + # translation units with default visibility; the C++ core stays hidden. + set_source_files_properties(${OBJC_WRAPPER_SRCS} + PROPERTIES COMPILE_FLAGS "-fvisibility=default") + endif() + if(MATSDK_OBJC_PRIVACYGUARD_AVAILABLE) target_compile_definitions(mat PRIVATE MATSDK_OBJC_PRIVACYGUARD_AVAILABLE=1) else() diff --git a/lib/android_build/maesdk/src/main/java/com/microsoft/applications/events/LogConfigurationKey.java b/lib/android_build/maesdk/src/main/java/com/microsoft/applications/events/LogConfigurationKey.java index 329f17680..0ce2881ef 100644 --- a/lib/android_build/maesdk/src/main/java/com/microsoft/applications/events/LogConfigurationKey.java +++ b/lib/android_build/maesdk/src/main/java/com/microsoft/applications/events/LogConfigurationKey.java @@ -29,6 +29,9 @@ public enum LogConfigurationKey { /** Enable network detector. */ CFG_BOOL_ENABLE_NET_DETECT("enableNetworkDetector", Boolean.class), + /** Scrub (obfuscate) the client IP address at the collector. Applied unless explicitly set to false (on by default; not present in the default configuration). */ + CFG_BOOL_ENABLE_IP_SCRUBBING("enableIpScrubbing", Boolean.class), + CFG_BOOL_TPM_CLOCK_SKEW_ENABLED("clockSkewEnabled", Boolean.class), /** Parameter that allows to check if the SDK is running on UTC mode */ diff --git a/lib/bond/CompactBinaryProtocolReader.hpp b/lib/bond/CompactBinaryProtocolReader.hpp index 612970421..708aba421 100644 --- a/lib/bond/CompactBinaryProtocolReader.hpp +++ b/lib/bond/CompactBinaryProtocolReader.hpp @@ -69,7 +69,7 @@ class CompactBinaryProtocolReader { return false; } #ifdef HAVE_ONEDS_BOUNDCHECK_METHODS - bool result = MAT::BoundCheckFunctions::oneds_memcpy_s(static_cast(data), size, &(m_input[m_ofs]), size); + bool result = (MAT::BoundCheckFunctions::oneds_memcpy_s(static_cast(data), size, &(m_input[m_ofs]), size) == 0); #else bool result = (memcpy_s(static_cast(data), size, &(m_input[m_ofs]), size) == 0); #endif diff --git a/lib/decorators/EventPropertiesDecorator.hpp b/lib/decorators/EventPropertiesDecorator.hpp index 5bb3e927a..800dc1635 100644 --- a/lib/decorators/EventPropertiesDecorator.hpp +++ b/lib/decorators/EventPropertiesDecorator.hpp @@ -6,6 +6,8 @@ #define EVENTPROPERTIESDECORATOR_HPP #include "IDecorator.hpp" +#include "ILogManager.hpp" +#include "RecordFlagConstants.hpp" #include "EventProperties.hpp" #include "CorrelationVector.hpp" #include "utils/Utils.hpp" @@ -16,15 +18,6 @@ namespace MAT_NS_BEGIN { -// Bit remapping has to happen on bits passed via API surface. -// Ref CS2.1+ : https://osgwiki.com/wiki/CommonSchema/flags -// #define MICROSOFT_EVENTTAG_MARK_PII 0x08000000 -#define RECORD_FLAGS_EVENTTAG_MARK_PII 0x00080000 -// #define MICROSOFT_EVENTTAG_HASH_PII 0x04000000 -#define RECORD_FLAGS_EVENTTAG_HASH_PII 0x00100000 -// #define MICROSOFT_EVENTTAG_DROP_PII 0x02000000 -#define RECORD_FLAGS_EVENTTAG_DROP_PII 0x00200000 - class EventPropertiesDecorator : public IDecorator { protected: @@ -125,6 +118,14 @@ namespace MAT_NS_BEGIN { int64_t tags = eventProperties.GetPolicyBitFlags(); int64_t flags = 0; + // Scrub/obfuscate the client IP address at the collector by default. + // Hosts that require the client IP (e.g. for geo-location enrichment) + // can opt out by setting CFG_BOOL_ENABLE_IP_SCRUBBING = false. + ILogConfiguration& config = m_owner.GetLogConfiguration(); + if (!config.HasConfig(CFG_BOOL_ENABLE_IP_SCRUBBING) || config[CFG_BOOL_ENABLE_IP_SCRUBBING]) + { + flags |= RECORD_FLAGS_EVENTTAG_SCRUB_IP; + } // We must remap from one bitfield set to another, no way to bit-shift :( // At the moment 1DS SDK in direct upload mode supports DROP and MARK tags only: flags |= (tags & MICROSOFT_EVENTTAG_MARK_PII) ? RECORD_FLAGS_EVENTTAG_MARK_PII : 0; diff --git a/lib/decorators/RecordFlagConstants.hpp b/lib/decorators/RecordFlagConstants.hpp new file mode 100644 index 000000000..8c0fe56d3 --- /dev/null +++ b/lib/decorators/RecordFlagConstants.hpp @@ -0,0 +1,30 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +#ifndef RECORDFLAGCONSTANTS_HPP +#define RECORDFLAGCONSTANTS_HPP + +#include "ctmacros.hpp" + +#include + +namespace MAT_NS_BEGIN { + + // On-wire CS protocol record.flags bits. These are distinct from the + // API-surface MICROSOFT_EVENTTAG_* policy flags and are remapped onto + // record.flags by EventPropertiesDecorator. Kept in a dedicated header so + // other components (e.g. the stats pipeline) can reference a single bit + // definition without depending on the decorator's inline implementation. + // Ref CS2.1+: https://osgwiki.com/wiki/CommonSchema/flags + // (API-surface MICROSOFT_EVENTTAG_MARK_PII 0x08000000) + static constexpr std::int64_t RECORD_FLAGS_EVENTTAG_MARK_PII = 0x00080000; + // (API-surface MICROSOFT_EVENTTAG_HASH_PII 0x04000000) + static constexpr std::int64_t RECORD_FLAGS_EVENTTAG_HASH_PII = 0x00100000; + // (API-surface MICROSOFT_EVENTTAG_DROP_PII 0x02000000) + static constexpr std::int64_t RECORD_FLAGS_EVENTTAG_DROP_PII = 0x00200000; + static constexpr std::int64_t RECORD_FLAGS_EVENTTAG_SCRUB_IP = 0x00400000; + +} MAT_NS_END + +#endif // RECORDFLAGCONSTANTS_HPP diff --git a/lib/http/HttpResponseDecoder.cpp b/lib/http/HttpResponseDecoder.cpp index 11e9d4096..6014cec19 100644 --- a/lib/http/HttpResponseDecoder.cpp +++ b/lib/http/HttpResponseDecoder.cpp @@ -91,6 +91,7 @@ namespace MAT_NS_BEGIN { DebugEvent evt; evt.type = DebugEventType::EVT_HTTP_OK; evt.param1 = response.GetStatusCode(); + evt.param2 = ctx->recordIdsAndTenantIds.size(); evt.data = static_cast(request.GetBody().data()); evt.size = request.GetBody().size(); DispatchEvent(evt); @@ -112,6 +113,7 @@ namespace MAT_NS_BEGIN { // This is to be addressed with ETW trace API that can send // a detailed error context to ETW provider. evt.param1 = response.GetStatusCode(); + evt.param2 = ctx->recordIdsAndTenantIds.size(); evt.data = static_cast(request.GetBody().data()); evt.size = request.GetBody().size(); DispatchEvent(evt); @@ -127,6 +129,7 @@ namespace MAT_NS_BEGIN { DebugEvent evt; evt.type = DebugEventType::EVT_HTTP_FAILURE; evt.param1 = 0; // response.GetStatusCode(); + evt.param2 = ctx->recordIdsAndTenantIds.size(); DispatchEvent(evt); } ctx->httpResponse = nullptr; @@ -144,6 +147,7 @@ namespace MAT_NS_BEGIN { DebugEvent evt; evt.type = DebugEventType::EVT_HTTP_FAILURE; evt.param1 = response.GetStatusCode(); + evt.param2 = ctx->recordIdsAndTenantIds.size(); DispatchEvent(evt); } temporaryServerFailure(ctx); @@ -157,6 +161,7 @@ namespace MAT_NS_BEGIN { DebugEvent evt; evt.type = DebugEventType::EVT_HTTP_FAILURE; evt.param1 = response.GetStatusCode(); + evt.param2 = ctx->recordIdsAndTenantIds.size(); DispatchEvent(evt); } temporaryNetworkFailure(ctx); @@ -253,4 +258,3 @@ namespace MAT_NS_BEGIN { } } MAT_NS_END - diff --git a/lib/include/public/ILogConfiguration.hpp b/lib/include/public/ILogConfiguration.hpp index 1cb8103b8..af1bc44c2 100644 --- a/lib/include/public/ILogConfiguration.hpp +++ b/lib/include/public/ILogConfiguration.hpp @@ -104,6 +104,16 @@ namespace MAT_NS_BEGIN /// static constexpr const char* const CFG_BOOL_ENABLE_NET_DETECT = "enableNetworkDetector"; + /// + /// Request collector-side scrubbing (obfuscation) of the client IP address. + /// Applied unless explicitly set to false (on by default; the key is not + /// present in the default configuration). Opt out when the client IP is + /// needed, e.g. for geo-location enrichment. Honored by the OneCollector + /// direct-upload path; in UTC mode client privacy is governed by the OS UTC + /// pipeline instead. + /// + static constexpr const char* const CFG_BOOL_ENABLE_IP_SCRUBBING = "enableIpScrubbing"; + /// /// Parameter that allows to check if the SDK is running on UTC mode /// diff --git a/lib/include/public/Version.hpp b/lib/include/public/Version.hpp index bb114f5a5..cf7ec9b99 100644 --- a/lib/include/public/Version.hpp +++ b/lib/include/public/Version.hpp @@ -6,8 +6,8 @@ #define MAT_VERSION_HPP // WARNING: DO NOT MODIFY THIS FILE! // This file has been automatically generated, manual changes will be lost. -#define BUILD_VERSION_STR "3.10.161.1" -#define BUILD_VERSION 3,10,161,1 +#define BUILD_VERSION_STR "3.10.173.1" +#define BUILD_VERSION 3,10,173,1 #ifndef RESOURCE_COMPILER_INVOKED #include "ctmacros.hpp" @@ -18,7 +18,7 @@ namespace MAT_NS_BEGIN { uint64_t const Version = ((uint64_t)3 << 48) | ((uint64_t)10 << 32) | - ((uint64_t)161 << 16) | + ((uint64_t)173 << 16) | ((uint64_t)1); } MAT_NS_END diff --git a/lib/include/public/ctmacros.hpp b/lib/include/public/ctmacros.hpp index 42547e41d..cabd36f5f 100644 --- a/lib/include/public/ctmacros.hpp +++ b/lib/include/public/ctmacros.hpp @@ -28,9 +28,14 @@ #define MATSDK_LIBABI_CDECL __cdecl # if defined(MATSDK_SHARED_LIB) # define MATSDK_LIBABI __declspec(dllexport) +# elif defined(MATSDK_IMPORT_LIB) +// Consumer importing the public API from a shared mat.dll. The installed +// MSTelemetry::mat CMake target propagates this automatically when the SDK was +// built shared (see lib/CMakeLists.txt). +# define MATSDK_LIBABI __declspec(dllimport) # elif defined(MATSDK_STATIC_LIB) # define MATSDK_LIBABI -# else // Header file included by client +# else // Header file included by client; linkage unspecified # ifndef MATSDK_LIBABI # define MATSDK_LIBABI # endif @@ -47,8 +52,19 @@ #define MATSDK_LIBABI_CDECL #endif -#ifndef MATSDK_LIBABI -#define MATSDK_LIBABI +#ifndef MATSDK_LIBABI +// Mark the public API as default-visibility ONLY in shared builds, so it stays +// exported when the SDK is compiled with -fvisibility=hidden (see CMakeLists.txt). +// This mirrors the __declspec(dllexport) gating above: in a static build the +// attribute is omitted, so the public symbols inherit -fvisibility=hidden and are +// NOT re-exported when a consumer .so/.dylib statically absorbs libmat. (When a +// consumer includes this header, MATSDK_SHARED_LIB is not defined either, which +// is fine: the symbols are exported by the shared libmat they link against.) +# if (defined(__GNUC__) || defined(__clang__)) && defined(MATSDK_SHARED_LIB) +# define MATSDK_LIBABI __attribute__((visibility("default"))) +# else +# define MATSDK_LIBABI +# endif #endif // TODO: [MG] - ideally we'd like to use __attribute__((unused)) with gcc/clang diff --git a/lib/offline/OfflineStorage_Room.cpp b/lib/offline/OfflineStorage_Room.cpp index 72a04d0ed..d052e7a9d 100644 --- a/lib/offline/OfflineStorage_Room.cpp +++ b/lib/offline/OfflineStorage_Room.cpp @@ -240,6 +240,14 @@ namespace MAT_NS_BEGIN MATSDK_THROW(std::logic_error("whereFilter not implemented")); } + if (!env) + { + return; + } + if (!m_room) + { + return; + } auto room_class = env->GetObjectClass(m_room); auto deleteByToken = env->GetMethodID(room_class, "deleteByToken", @@ -274,6 +282,10 @@ namespace MAT_NS_BEGIN { return; } + if (!m_room) + { + return; + } auto room_class = env->GetObjectClass(m_room); auto method = env->GetMethodID(room_class, "deleteById", "([J)J"); ThrowLogic(env, "Unable to get deleteById method"); @@ -377,6 +389,10 @@ namespace MAT_NS_BEGIN { return false; } + if (!m_room) + { + return false; + } auto room_class = env->GetObjectClass(m_room); auto reserve = env->GetMethodID(room_class, "getAndReserve", "(IJJJ)[Lcom/microsoft/applications/events/StorageRecord;"); @@ -424,11 +440,26 @@ namespace MAT_NS_BEGIN int persist_lb = static_cast(EventPersistence_Normal); int persist_ub = static_cast(EventPersistence_DoNotStoreOnDisk); + // Set if a null array element is hit below, so the early-release + // path skips releaseUnconsumed (which would index into the null). + bool sawNullElement = false; for (index = 0; index < limit; ++index) { env.pushLocalFrame(32); auto record = env->GetObjectArrayElement(selected, index); ThrowLogic(env, "getAndReserve element"); + if (!record) + { + // Null array element (observed with some androidx.room + // versions): pop this frame and stop rather than + // dereferencing null in GetObjectClass. We cannot safely + // release the tail here (it contains this null and Java + // releaseUnconsumed indexes from 0), so leave the + // remaining reservations to expire and be retried. + sawNullElement = true; + env.popLocalFrame(); + break; + } if (!record_class) { // Promote to a global ref so it survives popLocalFrame on @@ -518,11 +549,14 @@ namespace MAT_NS_BEGIN if (index < limit) { // we did not consume all these events - auto release = env->GetMethodID(room_class, "releaseUnconsumed", - "([Lcom/microsoft/applications/events/StorageRecord;I)V"); - ThrowLogic(env, "releaseUnconsumed"); - env->CallVoidMethod(m_room, release, selected, static_cast(index)); - ThrowRuntime(env, "call ru"); + if (!sawNullElement) + { + auto release = env->GetMethodID(room_class, "releaseUnconsumed", + "([Lcom/microsoft/applications/events/StorageRecord;I)V"); + ThrowLogic(env, "releaseUnconsumed"); + env->CallVoidMethod(m_room, release, selected, static_cast(index)); + ThrowRuntime(env, "call ru"); + } break; // break out of the request > collected loop--end early by request } } @@ -633,6 +667,14 @@ namespace MAT_NS_BEGIN try { ConnectedEnv env(s_vm); + if (!env) + { + return; + } + if (!m_room) + { + return; + } auto room_class = env->GetObjectClass(m_room); ThrowLogic(env, "GetObjectClass for m_room"); auto release = env->GetMethodID(room_class, @@ -700,6 +742,12 @@ namespace MAT_NS_BEGIN env.pushLocalFrame(8); auto byTenant = env->GetObjectArrayElement(results, index); ThrowRuntime(env, "Exception fetching element from results"); + if (!byTenant) + { + // Skip a null array element rather than dereference null. + env.popLocalFrame(); + continue; + } if (!bt_class) { // Promote to a global ref so it survives popLocalFrame. @@ -794,6 +842,10 @@ namespace MAT_NS_BEGIN static constexpr char newRecordSignature[] = "(JIIJIJ[B)Lcom/microsoft/applications/events/StorageRecord;"; + if (!m_room) + { + return 0; + } auto room_class = env->GetObjectClass(m_room); size_t count = std::min(records.size(), INT32_MAX); @@ -924,6 +976,14 @@ namespace MAT_NS_BEGIN try { ConnectedEnv env(s_vm); + if (!env) + { + return false; + } + if (!m_room) + { + return false; + } auto room_class = env->GetObjectClass(m_room); auto delete_method = env->GetMethodID(room_class, "deleteSetting", "(Ljava/lang/String;)V"); @@ -964,6 +1024,14 @@ namespace MAT_NS_BEGIN try { ConnectedEnv env(s_vm); + if (!env) + { + return false; + } + if (!m_room) + { + return false; + } auto room_class = env->GetObjectClass(m_room); jmethodID store_setting = env->GetMethodID( room_class, @@ -1081,6 +1149,10 @@ namespace MAT_NS_BEGIN size_t OfflineStorage_Room::GetSizeInternal(ConnectedEnv& env) const { + if (!m_room) + { + return 0; + } auto room_class = env->GetObjectClass(m_room); auto method = env->GetMethodID(room_class, "totalSize", "()J"); if (!method) @@ -1107,6 +1179,10 @@ namespace MAT_NS_BEGIN { return 0; } + if (!m_room) + { + return 0; + } auto room_class = env->GetObjectClass(m_room); auto count_id = env->GetMethodID(room_class, "getRecordCount", "(I)J"); ThrowLogic(env, "getRecordCount"); @@ -1162,6 +1238,10 @@ namespace MAT_NS_BEGIN { return false; } + if (!m_room) + { + return false; + } auto room_class = env->GetObjectClass(m_room); auto trim_id = env->GetMethodID(room_class, "trim", "(J)J"); ThrowLogic(env, "trim"); @@ -1192,6 +1272,14 @@ namespace MAT_NS_BEGIN { ConnectedEnv env(s_vm); + if (!env) + { + return records; + } + if (!m_room) + { + return records; + } auto room_class = env->GetObjectClass(m_room); auto method = env->GetMethodID(room_class, "getRecords", "(ZIJ)[Lcom/microsoft/applications/events/StorageRecord;"); diff --git a/lib/stats/Statistics.cpp b/lib/stats/Statistics.cpp index 773dd4d13..a1377ac37 100644 --- a/lib/stats/Statistics.cpp +++ b/lib/stats/Statistics.cpp @@ -9,6 +9,7 @@ #include "ILogManager.hpp" #include "mat/config.h" #include "utils/Utils.hpp" +#include "decorators/RecordFlagConstants.hpp" #include namespace MAT_NS_BEGIN { @@ -83,6 +84,13 @@ namespace MAT_NS_BEGIN { result &= m_baseDecorator.decorate(record); // Allow stats to capture Part A common properties, but not the custom result &= m_semanticContextDecorator.decorate(record, true); + // Stats events bypass EventPropertiesDecorator, so apply the same + // collector-side client-IP scrub here (on by default; opt out via + // CFG_BOOL_ENABLE_IP_SCRUBBING = false). + if (!m_config.HasConfig(CFG_BOOL_ENABLE_IP_SCRUBBING) || m_config[CFG_BOOL_ENABLE_IP_SCRUBBING]) + { + record.flags |= RECORD_FLAGS_EVENTTAG_SCRUB_IP; + } if (result) { IncomingEventContext evt(PAL::generateUuidString(), tenantToken, EventLatency_Normal, EventPersistence_Normal, &record); diff --git a/lib/system/EventProperty.cpp b/lib/system/EventProperty.cpp index 3bf9c3f3c..6d0582440 100644 --- a/lib/system/EventProperty.cpp +++ b/lib/system/EventProperty.cpp @@ -307,10 +307,13 @@ namespace MAT_NS_BEGIN { // How to sort 2 objects (needed for maps) bool GUID_t::operator<(GUID_t const& other) const { - return Data1 < other.Data1 || - Data2 < other.Data2 || - Data3 == other.Data3 || - (memcmp(Data4, other.Data4, sizeof(Data4)) < 0); + if (Data1 != other.Data1) + return Data1 < other.Data1; + if (Data2 != other.Data2) + return Data2 < other.Data2; + if (Data3 != other.Data3) + return Data3 < other.Data3; + return memcmp(Data4, other.Data4, sizeof(Data4)) < 0; } void EventProperty::copydata(EventProperty const* source) diff --git a/tests/unittests/EventPropertiesDecoratorTests.cpp b/tests/unittests/EventPropertiesDecoratorTests.cpp index f38444fd0..348354604 100644 --- a/tests/unittests/EventPropertiesDecoratorTests.cpp +++ b/tests/unittests/EventPropertiesDecoratorTests.cpp @@ -28,6 +28,19 @@ class TestEventPropertiesDecorator : public EventPropertiesDecorator } }; +// NullLogManager hands out a single shared static ILogConfiguration, which would +// leak configuration across tests. This subclass owns a per-instance configuration +// so the IP-scrubbing opt-out can be exercised in isolation. +class ConfigurableLogManager : public NullLogManager +{ +public: + ILogConfiguration localConfig; + ILogConfiguration& GetLogConfiguration() override + { + return localConfig; + } +}; + static std::unique_ptr PopulateRecordForDropPii() { auto record = std::unique_ptr(new Record{}); @@ -545,3 +558,41 @@ TEST(EventPropertiesDecoratorTests, DropPiiPartA_StripsValues) EXPECT_THAT(record->extSdk[0].installId, Eq("")); EXPECT_THAT(record->cV, Eq("")); } + +TEST(EventPropertiesDecoratorTests, Decorate_ScrubIp_EnabledByDefault) +{ + ConfigurableLogManager logManager; // CFG_BOOL_ENABLE_IP_SCRUBBING not set + EventPropertiesDecorator decorator(logManager); + Record record; + EventProperties props {"TestEvent"}; + EventLatency latency = EventLatency::EventLatency_Normal; + + EXPECT_TRUE(decorator.decorate(record, latency, props)); + EXPECT_TRUE(record.flags & RECORD_FLAGS_EVENTTAG_SCRUB_IP); +} + +TEST(EventPropertiesDecoratorTests, Decorate_ScrubIp_OptOutViaConfig) +{ + ConfigurableLogManager logManager; + logManager.localConfig[CFG_BOOL_ENABLE_IP_SCRUBBING] = false; + EventPropertiesDecorator decorator(logManager); + Record record; + EventProperties props {"TestEvent"}; + EventLatency latency = EventLatency::EventLatency_Normal; + + EXPECT_TRUE(decorator.decorate(record, latency, props)); + EXPECT_FALSE(record.flags & RECORD_FLAGS_EVENTTAG_SCRUB_IP); +} + +TEST(EventPropertiesDecoratorTests, Decorate_ScrubIp_ExplicitlyEnabled) +{ + ConfigurableLogManager logManager; + logManager.localConfig[CFG_BOOL_ENABLE_IP_SCRUBBING] = true; + EventPropertiesDecorator decorator(logManager); + Record record; + EventProperties props {"TestEvent"}; + EventLatency latency = EventLatency::EventLatency_Normal; + + EXPECT_TRUE(decorator.decorate(record, latency, props)); + EXPECT_TRUE(record.flags & RECORD_FLAGS_EVENTTAG_SCRUB_IP); +} diff --git a/tests/unittests/GuidTests.cpp b/tests/unittests/GuidTests.cpp index a0fc9fdb5..4a45d880c 100644 --- a/tests/unittests/GuidTests.cpp +++ b/tests/unittests/GuidTests.cpp @@ -7,6 +7,8 @@ #include "utils/Utils.hpp" #include "EventProperties.hpp" +#include + using namespace testing; using namespace MAT; @@ -84,4 +86,23 @@ TEST(GuidTests, MoveAssignment_ValidInput_MovesCorrectly) GUID_t second{"BEE391C8-72B0-464F-93C3-1B27879AD103"}; second = std::move(first); ASSERT_EQ("9D016D64-372E-4DCE-9FA3-0D0772217C54", second.to_string()); -} \ No newline at end of file +} +TEST(GuidTests, OperatorLess_IsStrictWeakOrdering) +{ + // a and b differ in Data1/Data2 such that a non-lexicographic chained-|| operator + // reported BOTH a < b and b < a (antisymmetry violation). + GUID_t a{ "00000001-0005-0000-0000-000000000000" }; + GUID_t b{ "00000002-0003-0000-0000-000000000000" }; + EXPECT_TRUE(a < b); + EXPECT_FALSE(b < a); + + // c and d differ ONLY in Data3; a '==' in that position made them compare equivalent. + GUID_t c{ "00000001-0001-0001-0000-000000000000" }; + GUID_t d{ "00000001-0001-0002-0000-000000000000" }; + EXPECT_TRUE(c < d); + EXPECT_FALSE(d < c); + + // A std::set keyed on operator< must keep four distinct GUIDs distinct. + std::set s{ a, b, c, d }; + EXPECT_EQ(static_cast(4), s.size()); +} diff --git a/tools/apple/MATTelemetry-umbrella.h b/tools/apple/MATTelemetry-umbrella.h new file mode 100644 index 000000000..8d4aaf952 --- /dev/null +++ b/tools/apple/MATTelemetry-umbrella.h @@ -0,0 +1,24 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Umbrella header for the Obj-C surface vended by MATTelemetry.xcframework. +// +// build-xcframework.sh flattens the ODW*.h headers into the framework's +// Headers/ directory, so these are imported by bare name (not by the +// ../../obj-c/ relative path the in-repo Swift bridging header uses). +// +// This template intentionally lists only always-available Obj-C headers. +// build-xcframework.sh appends imports for optional module headers only when +// those modules were actually built into the binary. + +#import + +#import "ODWCommonDataContext.h" +#import "ODWEventProperties.h" +#import "ODWLogConfiguration.h" +#import "ODWLogger.h" +#import "ODWLogManager.h" +#import "ODWPrivacyGuardInitConfig.h" +#import "ODWSanitizerInitConfig.h" +#import "ODWSemanticContext.h" diff --git a/tools/apple/MATTelemetryAvailability.json b/tools/apple/MATTelemetryAvailability.json new file mode 100644 index 000000000..34cb38831 --- /dev/null +++ b/tools/apple/MATTelemetryAvailability.json @@ -0,0 +1,5 @@ +{ + "diagnosticDataViewer": false, + "privacyGuard": false, + "sanitizer": false +} diff --git a/tools/apple/README.md b/tools/apple/README.md new file mode 100644 index 000000000..79d706fd1 --- /dev/null +++ b/tools/apple/README.md @@ -0,0 +1,121 @@ +# Swift Package Manager xcframework prototype + +This package distributes the 1DS C++ SDK to Apple developers through Swift +Package Manager (SPM), using a prebuilt xcframework for the C++ core plus Obj-C +wrappers and compiling the Swift API from source. + +## Package shape + +SPM is not a good fit for compiling this SDK's full C++ tree directly because +the SDK depends on CMake, Bond codegen, vendored sqlite3/zlib, and platform +conditionals. Instead, the package is split into: + +| Layer | Packaging | +| --- | --- | +| C++ core + Obj-C wrappers (`ODW*`) | `MATTelemetry.xcframework` binary target | +| Swift API (`OneDSSwift`) | Source target in `wrappers/swift/Sources/OneDSSwift` | + +The xcframework vendors a Clang module named `MATTelemetryObjC` through +`tools/apple/module.modulemap` and `MATTelemetry-umbrella.h`, matching the +existing Swift sources' `import MATTelemetryObjC`. + +## Runtime dependencies (sqlite3 / zlib) + +The xcframework does **not** bundle sqlite3 or zlib. `Package.swift` links the +**system** `libsqlite3` and `libz` that Apple ships on every iOS / macOS / Mac +Catalyst / visionOS target (`.linkedLibrary("sqlite3")` / `.linkedLibrary("z")`), +so consumers do not need to add them. + +This is deliberate. Embedding a private static copy of sqlite3 into the +xcframework would give any app that also uses SQLite (Core Data, GRDB, FMDB, +etc.) two copies of the library in one process — risking duplicate-symbol link +errors or divergent SQLite state. Linking the OS-provided libraries guarantees a +single shared instance. For comparison, the vcpkg build consumes vcpkg's own +sqlite3/zlib packages, and only the Android build bundles them (the NDK ships no +system copy). + +## Supported slices + +`tools/apple/build-xcframework.sh release` builds: + +| Platform | Slice | +| --- | --- | +| iOS device | `ios-arm64` | +| iOS Simulator | `ios-arm64_x86_64-simulator` | +| Mac Catalyst | `ios-arm64_x86_64-maccatalyst` | +| macOS | `macos-arm64_x86_64` | +| visionOS device | `xros-arm64` | +| visionOS Simulator | `xros-arm64-simulator` | + +## Important files + +| File | Purpose | +| --- | --- | +| `Package.swift` | Root SPM manifest: binary target + Swift source target | +| `tools/apple/build-xcframework.sh` | Builds static `libmat.a` slices and assembles `MATTelemetry.xcframework` | +| `tools/apple/module.modulemap` | Defines the `MATTelemetryObjC` Clang module | +| `tools/apple/MATTelemetry-umbrella.h` | Base umbrella for always-available Obj-C wrapper headers | +| `tools/apple/MATTelemetryAvailability.json` | Optional-module manifest consumed by `Package.swift` | +| `.github/workflows/spm-release.yml` | Release automation for the hosted xcframework and SPM tag | + +## Local build + +Run on macOS with Xcode and CMake: + +```bash +tools/apple/build-xcframework.sh release +# -> build/apple/MATTelemetry.xcframework +# -> build/apple/MATTelemetry.xcframework.zip +# -> prints the SwiftPM checksum +``` + +For local development, `Package.swift` points at +`build/apple/MATTelemetry.xcframework`. `swift build` validates macOS +consumption; use Xcode destinations for iOS Simulator, Mac Catalyst, and +visionOS Simulator. + +## Consumption + +- **Local:** add this repository as a local package dependency after building + `build/apple/MATTelemetry.xcframework`. +- **Released:** add the repository URL in Xcode and pin the parallel + 3-component SemVer tag published by the release workflow: + +```swift +.package(url: "https://github.com/microsoft/cpp_client_telemetry.git", from: "3.10.161") +``` + +The SDK's native release tags are 4-component (`vX.Y.Z.W`), which SPM does not +accept as SemVer. The release workflow publishes the corresponding `X.Y.Z` tag. + +## Release workflow + +`.github/workflows/spm-release.yml` runs for published SDK releases and manual +dispatch. It: + +1. Builds and zips `MATTelemetry.xcframework`. +2. Validates package consumption for macOS, iOS Simulator, Mac Catalyst, and + visionOS Simulator. +3. Uploads the zip to the GitHub Release. +4. Rewrites `Package.swift` from local `path:` to hosted `url:` + `checksum:`. +5. Commits the resolved manifest and pushes the 3-component SPM tag. + +The private `lib/modules` submodule is intentionally not fetched by the release +workflow, so optional module headers and Swift sources are gated by +`MATTelemetryAvailability.json`. + +## Validation performed + +- Full xcframework build for iOS, iOS Simulator, Mac Catalyst, macOS, visionOS, + and visionOS Simulator. +- SwiftPM/Xcode builds for macOS, iOS Simulator, Mac Catalyst, visionOS + Simulator, and visionOS device. +- External TelemetryTest package consumer builds, including visionOS. +- Obj-C module/static-link smoke tests for representative binary slices. +- Apple Vision Pro simulator runtime installation and boot. + +## Known gaps + +- Release xcframework signing/notarization. +- End-to-end execution of `.github/workflows/spm-release.yml` on a real + published release. diff --git a/tools/apple/build-xcframework.sh b/tools/apple/build-xcframework.sh new file mode 100755 index 000000000..7fed4ccf9 --- /dev/null +++ b/tools/apple/build-xcframework.sh @@ -0,0 +1,202 @@ +#!/bin/bash +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# PROTOTYPE: build MATTelemetry.xcframework (1DS C++ core + Obj-C wrappers) for +# Apple platforms, for Swift Package Manager distribution. +# +# Run on macOS with Xcode + CMake installed. Usage: +# tools/apple/build-xcframework.sh [release|debug] +# +# Produces: +# build/apple/MATTelemetry.xcframework +# build/apple/MATTelemetry.xcframework.zip (+ prints the SPM checksum) +# +# Slices built here: iOS device (arm64), iOS simulator (arm64 + x86_64 fat), +# Mac Catalyst (arm64 + x86_64 fat), visionOS device/simulator (arm64), and +# macOS (arm64 + x86_64 universal). +# +# NOTE: this is a first-pass scaffold. It has been validated on macOS for iOS +# device, simulator, Mac Catalyst, visionOS, and macOS slices. + +set -euo pipefail + +CONFIG="${1:-release}" +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +OUT="$ROOT/build/apple" +LIB="libmat.a" # mat target; the Obj-C wrappers compile into it. + +case "$CONFIG" in + release) CMAKE_BUILD_TYPE="Release" ;; + debug) CMAKE_BUILD_TYPE="Debug" ;; + *) + echo "Usage: $0 [release|debug]" >&2 + exit 1 + ;; +esac + +# Build only the static libmat archive with Obj-C wrappers; slice builds do not +# need the repo's test, Swift wrapper, or package targets. +CMAKE_OPTS="${CMAKE_OPTS:-}" +CMAKE_OPTS="$CMAKE_OPTS -DBUILD_SHARED_LIBS=OFF" +CMAKE_OPTS="$CMAKE_OPTS -DBUILD_OBJC_WRAPPER=YES" +CMAKE_OPTS="$CMAKE_OPTS -DBUILD_TEST_TOOL=OFF" +CMAKE_OPTS="$CMAKE_OPTS -DBUILD_UNIT_TESTS=OFF" +CMAKE_OPTS="$CMAKE_OPTS -DBUILD_FUNC_TESTS=OFF" +CMAKE_OPTS="$CMAKE_OPTS -DBUILD_SWIFT_WRAPPER=OFF" +CMAKE_OPTS="$CMAKE_OPTS -DBUILD_PACKAGE=OFF" +export CMAKE_OPTS + +rm -rf "$OUT" +mkdir -p "$OUT" + +# --- 1. Public Obj-C headers + module map (vended by the xcframework) -------- +# Flatten the ODW*.h headers + umbrella + modulemap into one Headers dir. The +# module is named `MATTelemetryObjC` to match what wrappers/swift sources import. +HDRS="$OUT/Headers" +mkdir -p "$HDRS" + +has_dataviewer=false +has_privacyguard=false +has_sanitizer=false + +cmake_option_enabled() { # option-name default-value + local option="$1" + local value="$2" + local token + for token in $CMAKE_OPTS; do + case "$token" in + -D${option}=*) value="${token#*=}" ;; + -D${option}) value=ON ;; + esac + done + value="$(printf '%s' "$value" | tr '[:upper:]' '[:lower:]')" + case "$value" in + 0|false|no|off) return 1 ;; + *) return 0 ;; + esac +} + +[[ -d "$ROOT/lib/modules/dataviewer" ]] && has_dataviewer=true +if [[ -d "$ROOT/lib/modules/privacyguard" ]] && cmake_option_enabled BUILD_PRIVACYGUARD ON; then + has_privacyguard=true +fi +if [[ -d "$ROOT/lib/modules/sanitizer" ]] && cmake_option_enabled BUILD_SANITIZER ON; then + has_sanitizer=true +fi + +cat > "$OUT/MATTelemetryAvailability.json" <> "$HDRS/MATTelemetry-umbrella.h" + +# --- 2. Build one static lib per (arch, platform) ---------------------------- +build_slice() { # arch platform out-subdir + local arch="$1" plat="$2" sub="$3" + echo "=== building $arch / $plat ($CONFIG) ===" + ( + cd "$ROOT" + rm -rf out + MATTELEMETRY_SKIP_PACKAGE=1 ./build-ios.sh "$CONFIG" "$arch" "$plat" + ) + mkdir -p "$OUT/$sub" + cp "$ROOT/out/lib/$LIB" "$OUT/$sub/$LIB" +} + +build_slice arm64 iphoneos ios-arm64 +build_slice arm64 iphonesimulator ios-arm64-sim +build_slice x86_64 iphonesimulator ios-x86_64-sim +build_slice arm64 maccatalyst maccatalyst-arm64 +build_slice x86_64 maccatalyst maccatalyst-x86_64 +build_slice arm64 xros visionos-arm64 +build_slice arm64 xrsimulator visionos-arm64-sim + +# Fat simulator archive (arm64 + x86_64) -- a single xcframework slice cannot +# mix device and simulator, but it can contain multiple archs for one platform. +mkdir -p "$OUT/ios-simulator" +lipo -create "$OUT/ios-arm64-sim/$LIB" "$OUT/ios-x86_64-sim/$LIB" \ + -output "$OUT/ios-simulator/$LIB" + +# Fat Catalyst archive (arm64 + x86_64), emitted as a separate platform variant +# from both iOS simulator and native macOS. +mkdir -p "$OUT/maccatalyst" +lipo -create "$OUT/maccatalyst-arm64/$LIB" "$OUT/maccatalyst-x86_64/$LIB" \ + -output "$OUT/maccatalyst/$LIB" + +# Native universal macOS archive. Build only the `mat` target in an isolated +# CMake build directory so switching away from the iOS toolchain does not +# disturb the already-copied iOS archives. +echo "=== building arm64+x86_64 / macosx ($CONFIG) ===" +MACOS_BUILD="$OUT/macos-build" +MACOS_DEPLOYMENT_TARGET="${MACOSX_DEPLOYMENT_TARGET:-10.15}" +cmake -S "$ROOT" -B "$MACOS_BUILD" \ + -DMAC_ARCH=universal \ + -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" \ + -DCMAKE_OSX_DEPLOYMENT_TARGET="$MACOS_DEPLOYMENT_TARGET" \ + -DCMAKE_BUILD_TYPE="$CMAKE_BUILD_TYPE" \ + -DCMAKE_PACKAGE_TYPE=tgz \ + -DBUILD_TEST_TOOL=OFF \ + -DBUILD_UNIT_TESTS=OFF \ + -DBUILD_FUNC_TESTS=OFF \ + -DBUILD_SWIFT_WRAPPER=OFF \ + $CMAKE_OPTS +cmake --build "$MACOS_BUILD" --target mat +mkdir -p "$OUT/macos-universal" +cp "$MACOS_BUILD/lib/$LIB" "$OUT/macos-universal/$LIB" + +# --- 3. Assemble the xcframework --------------------------------------------- +rm -rf "$OUT/MATTelemetry.xcframework" +xcodebuild -create-xcframework \ + -library "$OUT/ios-arm64/$LIB" -headers "$HDRS" \ + -library "$OUT/ios-simulator/$LIB" -headers "$HDRS" \ + -library "$OUT/maccatalyst/$LIB" -headers "$HDRS" \ + -library "$OUT/visionos-arm64/$LIB" -headers "$HDRS" \ + -library "$OUT/visionos-arm64-sim/$LIB" -headers "$HDRS" \ + -library "$OUT/macos-universal/$LIB" -headers "$HDRS" \ + -output "$OUT/MATTelemetry.xcframework" +echo "Created $OUT/MATTelemetry.xcframework" + +# --- 4. Zip + checksum for release distribution ------------------------------ +( cd "$OUT" && rm -f MATTelemetry.xcframework.zip \ + && zip -qry MATTelemetry.xcframework.zip MATTelemetry.xcframework ) +echo "Zipped: $OUT/MATTelemetry.xcframework.zip" +echo -n "SPM checksum (for Package.swift binaryTarget url: form): " +swift package compute-checksum "$OUT/MATTelemetry.xcframework.zip" diff --git a/tools/apple/module.modulemap b/tools/apple/module.modulemap new file mode 100644 index 000000000..ec2e84f22 --- /dev/null +++ b/tools/apple/module.modulemap @@ -0,0 +1,9 @@ +// Clang module vended by MATTelemetry.xcframework. Imported by the OneDSSwift +// Swift layer as `import MATTelemetryObjC`. The module name is kept identical +// to the one in wrappers/swift/Modules/module.modulemap so the same Swift +// sources compile against both the local modulemap and this xcframework. + +module MATTelemetryObjC { + umbrella header "MATTelemetry-umbrella.h" + export * +} diff --git a/tools/ports/cpp-client-telemetry/portfile.cmake b/tools/ports/cpp-client-telemetry/portfile.cmake index b0ce77107..cfdab2368 100644 --- a/tools/ports/cpp-client-telemetry/portfile.cmake +++ b/tools/ports/cpp-client-telemetry/portfile.cmake @@ -1,8 +1,8 @@ vcpkg_from_github( OUT_SOURCE_PATH SOURCE_PATH REPO microsoft/cpp_client_telemetry - REF 4485b82005abf1d24336ace99b11df88dd578eb0 - SHA512 1f3ee1c26f1ae9e7323262c9b4c8796efba2c6addcde432d6c6c77b8c1c2f254cb8ff334b1dd0a72dc8ecfbfbae04ab374ec5ac7e5d286d6042953d53e50fd5b + REF v3.10.161.1 + SHA512 4664b34ddce601d6a95669df4a59d11a6cc67de1f23de132192f791a275edc6a10b8498d340e6cf7d120d9e7a22c494d7517b24fc0954bf9e236e84a8800589a HEAD_REF main ) @@ -46,8 +46,5 @@ vcpkg_cmake_config_fixup(PACKAGE_NAME MSTelemetry CONFIG_PATH lib/cmake/MSTeleme file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/debug/include") file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/debug/share") -# Install usage instructions -file(INSTALL "${CMAKE_CURRENT_LIST_DIR}/usage" DESTINATION "${CURRENT_PACKAGES_DIR}/share/${PORT}") - # Install license vcpkg_install_copyright(FILE_LIST "${SOURCE_PATH}/LICENSE") diff --git a/tools/ports/cpp-client-telemetry/usage b/tools/ports/cpp-client-telemetry/usage deleted file mode 100644 index 736d289f6..000000000 --- a/tools/ports/cpp-client-telemetry/usage +++ /dev/null @@ -1,4 +0,0 @@ -cpp-client-telemetry provides CMake targets: - - find_package(MSTelemetry CONFIG REQUIRED) - target_link_libraries(main PRIVATE MSTelemetry::mat) diff --git a/tools/ports/cpp-client-telemetry/vcpkg.json b/tools/ports/cpp-client-telemetry/vcpkg.json index d721df65a..2ee6d9bc3 100644 --- a/tools/ports/cpp-client-telemetry/vcpkg.json +++ b/tools/ports/cpp-client-telemetry/vcpkg.json @@ -6,9 +6,6 @@ "license": "Apache-2.0", "supports": "((windows & !mingw) | linux | osx | ios | android) & !uwp", "dependencies": [ - "nlohmann-json", - "sqlite3", - "zlib", { "name": "curl", "default-features": false, @@ -17,6 +14,11 @@ ], "platform": "linux | android" }, + "nlohmann-json", + { + "name": "sqlite3", + "default-features": false + }, { "name": "vcpkg-cmake", "host": true @@ -24,6 +26,7 @@ { "name": "vcpkg-cmake-config", "host": true - } + }, + "zlib" ] } diff --git a/wrappers/obj-c/ODWLogConfiguration.h b/wrappers/obj-c/ODWLogConfiguration.h index 3cbdaaa61..6e3f77946 100644 --- a/wrappers/obj-c/ODWLogConfiguration.h +++ b/wrappers/obj-c/ODWLogConfiguration.h @@ -44,6 +44,11 @@ extern NSString * _Nonnull const ODWCFG_BOOL_ENABLE_WAL_JOURNAL; */ extern NSString * _Nonnull const ODWCFG_BOOL_ENABLE_NET_DETECT; +/*! + Scrub (obfuscate) the client IP address at the collector. Applied unless explicitly set to false (on by default; not present in the default configuration). +*/ +extern NSString * _Nonnull const ODWCFG_BOOL_ENABLE_IP_SCRUBBING; + /*! The event collection URI. */ diff --git a/wrappers/obj-c/ODWLogConfiguration.mm b/wrappers/obj-c/ODWLogConfiguration.mm index d69ddf70c..611b92940 100644 --- a/wrappers/obj-c/ODWLogConfiguration.mm +++ b/wrappers/obj-c/ODWLogConfiguration.mm @@ -50,6 +50,11 @@ */ NSString *const ODWCFG_BOOL_ENABLE_NET_DETECT = @"enableNetworkDetector"; +/*! + Scrub (obfuscate) the client IP address at the collector. Applied unless explicitly set to false (on by default; not present in the default configuration). +*/ +NSString *const ODWCFG_BOOL_ENABLE_IP_SCRUBBING = @"enableIpScrubbing"; + /*! The event collection URI. */ diff --git a/wrappers/swift/Headers/ObjCModule-Bridging-Header.h b/wrappers/swift/Headers/MATTelemetryObjC-Bridging-Header.h similarity index 100% rename from wrappers/swift/Headers/ObjCModule-Bridging-Header.h rename to wrappers/swift/Headers/MATTelemetryObjC-Bridging-Header.h diff --git a/wrappers/swift/Modules/module.modulemap b/wrappers/swift/Modules/module.modulemap index 2e1856bae..f4fbec71d 100644 --- a/wrappers/swift/Modules/module.modulemap +++ b/wrappers/swift/Modules/module.modulemap @@ -1,6 +1,6 @@ /// Module exporting headers declared in ObjC. Imported by Swift package to have access to the ObjC types. -module ObjCModule { - header "../Headers/ObjCModule-Bridging-Header.h" +module MATTelemetryObjC { + header "../Headers/MATTelemetryObjC-Bridging-Header.h" export * } diff --git a/wrappers/swift/Package.swift b/wrappers/swift/Package.swift index 879943354..5547c5c4d 100644 --- a/wrappers/swift/Package.swift +++ b/wrappers/swift/Package.swift @@ -25,7 +25,6 @@ if hasPrivacyGuard { swiftSettings.append(.define("MATSDK_PRIVACYGUARD_AVAILABLE")) } else { excludedSources.append(contentsOf: [ - "CommonDataContext.swift", "PrivacyGuard.swift", "PrivacyGuardInitConfig.swift", ]) diff --git a/wrappers/swift/Sources/OneDSSwift/CommonDataContext.swift b/wrappers/swift/Sources/OneDSSwift/CommonDataContext.swift index 88786ac95..74c5bf0d0 100644 --- a/wrappers/swift/Sources/OneDSSwift/CommonDataContext.swift +++ b/wrappers/swift/Sources/OneDSSwift/CommonDataContext.swift @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -import ObjCModule +import MATTelemetryObjC /// Wrapper over ODWCommonDataContext class. public final class CommonDataContext { diff --git a/wrappers/swift/Sources/OneDSSwift/DiagnosticDataViewer.swift b/wrappers/swift/Sources/OneDSSwift/DiagnosticDataViewer.swift index 46d3011e9..dc136b076 100644 --- a/wrappers/swift/Sources/OneDSSwift/DiagnosticDataViewer.swift +++ b/wrappers/swift/Sources/OneDSSwift/DiagnosticDataViewer.swift @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -import ObjCModule +import MATTelemetryObjC /// Wrapper class over `ODWDiagnosticDataViewer` representing Diagnostic Data Viewer Hook. public final class DiagnosticDataViewer { diff --git a/wrappers/swift/Sources/OneDSSwift/EventProperties.swift b/wrappers/swift/Sources/OneDSSwift/EventProperties.swift index eb346a84e..bee46e573 100644 --- a/wrappers/swift/Sources/OneDSSwift/EventProperties.swift +++ b/wrappers/swift/Sources/OneDSSwift/EventProperties.swift @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -import ObjCModule +import MATTelemetryObjC /** Represents Event's properties. diff --git a/wrappers/swift/Sources/OneDSSwift/LogConfiguration.swift b/wrappers/swift/Sources/OneDSSwift/LogConfiguration.swift index 0f6bd18bb..1a5812770 100644 --- a/wrappers/swift/Sources/OneDSSwift/LogConfiguration.swift +++ b/wrappers/swift/Sources/OneDSSwift/LogConfiguration.swift @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -import ObjCModule +import MATTelemetryObjC /// Class wrapping `ODWLogConfiguration` ObjC class object, representing configuration related to events. public final class LogConfiguration { diff --git a/wrappers/swift/Sources/OneDSSwift/LogManager.swift b/wrappers/swift/Sources/OneDSSwift/LogManager.swift index 11a0af415..5a659795f 100644 --- a/wrappers/swift/Sources/OneDSSwift/LogManager.swift +++ b/wrappers/swift/Sources/OneDSSwift/LogManager.swift @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -import ObjCModule +import MATTelemetryObjC /// Wrapper over ODWLogManager which manages the telemetry logging system. public final class LogManager { diff --git a/wrappers/swift/Sources/OneDSSwift/Logger.swift b/wrappers/swift/Sources/OneDSSwift/Logger.swift index 04a9c1497..b901cfa4b 100644 --- a/wrappers/swift/Sources/OneDSSwift/Logger.swift +++ b/wrappers/swift/Sources/OneDSSwift/Logger.swift @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -import ObjCModule +import MATTelemetryObjC /// Wrapper class around ObjC Logger class `ODWLogger` used to events. public final class Logger { diff --git a/wrappers/swift/Sources/OneDSSwift/ObjCTypes.swift b/wrappers/swift/Sources/OneDSSwift/ObjCTypes.swift index 1042a42e1..e0e446b00 100644 --- a/wrappers/swift/Sources/OneDSSwift/ObjCTypes.swift +++ b/wrappers/swift/Sources/OneDSSwift/ObjCTypes.swift @@ -5,12 +5,12 @@ /// Contains alias for the types declared in the ObjC header files to make them available /// as part of the swift package module. -/// To avoid clients not have to import ObjCModule explicitly. +/// This lets clients use the Swift package module without importing MATTelemetryObjC explicitly. /// Important: Due to objc->swift conventions, Type name is removed, so ODWPiiKindGenericData would be accessed as .genericData in swift. /// Check corresponding header file for the doc of each type. -import ObjCModule +import MATTelemetryObjC // ODWEventProperties.h public typealias EventPriority = ODWEventPriority @@ -27,4 +27,6 @@ public typealias TransmissionProfile = ODWTransmissionProfile public typealias FlushStatus = ODWStatus // ODWPrivacyGuard.h +#if MATSDK_PRIVACYGUARD_AVAILABLE public typealias DataConcernType = ODWDataConcernType +#endif diff --git a/wrappers/swift/Sources/OneDSSwift/PrivacyGuard.swift b/wrappers/swift/Sources/OneDSSwift/PrivacyGuard.swift index 19ad4787a..b589b82bc 100644 --- a/wrappers/swift/Sources/OneDSSwift/PrivacyGuard.swift +++ b/wrappers/swift/Sources/OneDSSwift/PrivacyGuard.swift @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -import ObjCModule +import MATTelemetryObjC /// Wrapper to `ODWPrivacyGuard` representing Privacy Guard Hook. public final class PrivacyGuard { diff --git a/wrappers/swift/Sources/OneDSSwift/PrivacyGuardInitConfig.swift b/wrappers/swift/Sources/OneDSSwift/PrivacyGuardInitConfig.swift index 7f660d9f6..2459c7f08 100644 --- a/wrappers/swift/Sources/OneDSSwift/PrivacyGuardInitConfig.swift +++ b/wrappers/swift/Sources/OneDSSwift/PrivacyGuardInitConfig.swift @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -import ObjCModule +import MATTelemetryObjC public final class PrivacyGuardInitConfig { let odwPrivacyGuardInitConfig: ODWPrivacyGuardInitConfig diff --git a/wrappers/swift/Sources/OneDSSwift/Sanitizer.swift b/wrappers/swift/Sources/OneDSSwift/Sanitizer.swift index 4b5035f3c..004166f16 100644 --- a/wrappers/swift/Sources/OneDSSwift/Sanitizer.swift +++ b/wrappers/swift/Sources/OneDSSwift/Sanitizer.swift @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -import ObjCModule +import MATTelemetryObjC /// Wrapper to `ODWSanitizer` representing the Sanitizer. public final class Sanitizer { diff --git a/wrappers/swift/Sources/OneDSSwift/SanitizerInitConfig.swift b/wrappers/swift/Sources/OneDSSwift/SanitizerInitConfig.swift index 8eb70fd37..81f23d75b 100644 --- a/wrappers/swift/Sources/OneDSSwift/SanitizerInitConfig.swift +++ b/wrappers/swift/Sources/OneDSSwift/SanitizerInitConfig.swift @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -import ObjCModule +import MATTelemetryObjC public final class SanitizerInitConfig { let odwSanitizerInitConfig: ODWSanitizerInitConfig diff --git a/wrappers/swift/Sources/OneDSSwift/SemanticContext.swift b/wrappers/swift/Sources/OneDSSwift/SemanticContext.swift index 184d19bc4..3bf485fdf 100644 --- a/wrappers/swift/Sources/OneDSSwift/SemanticContext.swift +++ b/wrappers/swift/Sources/OneDSSwift/SemanticContext.swift @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -import ObjCModule +import MATTelemetryObjC /// Wrapper over `ODWSemanticContext` class that manages the inclusion of semantic context values on logged events. public class SemanticContext { @@ -49,11 +49,11 @@ public class SemanticContext { - Parameters: - userID: A `String` that contains the unique user identifier. - - withPiiKind: A PIIKind of the userID. Set it to PiiKind_None t odenote it as non-PII. - - Note: Default value is `ODWPiiKind.identity`. + - withPiiKind: A `PIIKind` for the userID. Set it to `PIIKind.none` to denote it as non-PII. + - Note: Default value is `PIIKind.identity`. */ - public func setUserID(_ userID: String, withPiiKind piiKind: ODWPiiKind = ODWPiiKind.identity) { - odwSemanticContext.setUserId(userID) + public func setUserID(_ userID: String, withPiiKind piiKind: PIIKind = PIIKind.identity) { + odwSemanticContext.setUserId(userID, piiKind: piiKind) } /**