summaryrefslogtreecommitdiff
path: root/src/gstreamer/gstlibcameraprovider.h
diff options
context:
space:
mode:
authorLaurent Pinchart <laurent.pinchart@ideasonboard.com>2024-05-31 14:24:24 +0300
committerLaurent Pinchart <laurent.pinchart@ideasonboard.com>2024-05-31 20:05:10 +0300
commit5d2c8fa11b921a650584d82d5c98c4b06eee990a (patch)
tree94e8a39e26b95e0f1908ace772745585b210c891 /src/gstreamer/gstlibcameraprovider.h
parentb8b24c5b5e02fc6b195ab0acab43f63ddeac8fbc (diff)
utils: checkstyle.py: Extend IncludeChecker to cover math.h
math.h is an exception to the C compatibility header rule, as we prefer using cmath. Extend the IncludeCheck to warn about it. Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com> Reviewed-by: Paul Elder <paul.elder@ideasonboard.com> Reviewed-by: Kieran Bingham <kieran.bingham@ideasonboard.com>
Diffstat (limited to 'src/gstreamer/gstlibcameraprovider.h')
0 files changed, 0 insertions, 0 deletions
='n83' href='#n83'>83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2019, Google Inc.
 *
 * ipa_module.cpp - Image Processing Algorithm module
 */

#include "libcamera/internal/ipa_module.h"

#include <algorithm>
#include <array>
#include <ctype.h>
#include <dlfcn.h>
#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <link.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <libcamera/span.h>

#include "libcamera/internal/file.h"
#include "libcamera/internal/log.h"
#include "libcamera/internal/pipeline_handler.h"
#include "libcamera/internal/utils.h"

/**
 * \file ipa_module.h
 * \brief Image Processing Algorithm module
 */

/**
 * \file ipa_module_info.h
 * \brief Image Processing Algorithm module information
 */

namespace libcamera {

LOG_DEFINE_CATEGORY(IPAModule)

namespace {

template<typename T>
typename std::remove_extent_t<T> *elfPointer(Span<const uint8_t> elf,
					     off_t offset, size_t objSize)
{
	size_t size = offset + objSize;
	if (size > elf.size() || size < objSize)
		return nullptr;

	return reinterpret_cast<typename std::remove_extent_t<T> *>
		(reinterpret_cast<const char *>(elf.data()) + offset);
}

template<typename T>
typename std::remove_extent_t<T> *elfPointer(Span<const uint8_t> elf,
					     off_t offset)
{
	return elfPointer<T>(elf, offset, sizeof(T));
}

int elfVerifyIdent(Span<const uint8_t> elf)
{
	const char *e_ident = elfPointer<const char[EI_NIDENT]>(elf, 0);
	if (!e_ident)
		return -ENOEXEC;

	if (e_ident[EI_MAG0] != ELFMAG0 ||
	    e_ident[EI_MAG1] != ELFMAG1 ||
	    e_ident[EI_MAG2] != ELFMAG2 ||
	    e_ident[EI_MAG3] != ELFMAG3 ||
	    e_ident[EI_VERSION] != EV_CURRENT)
		return -ENOEXEC;

	int bitClass = sizeof(unsigned long) == 4 ? ELFCLASS32 : ELFCLASS64;
	if (e_ident[EI_CLASS] != bitClass)
		return -ENOEXEC;

	int a = 1;
	unsigned char endianness = *reinterpret_cast<char *>(&a) == 1
				 ? ELFDATA2LSB : ELFDATA2MSB;
	if (e_ident[EI_DATA] != endianness)
		return -ENOEXEC;

	return 0;
}

const ElfW(Shdr) *elfSection(Span<const uint8_t> elf, const ElfW(Ehdr) *eHdr,
			     ElfW(Half) idx)
{
	if (idx >= eHdr->e_shnum)
		return nullptr;

	off_t offset = eHdr->e_shoff + idx *
				       static_cast<uint32_t>(eHdr->e_shentsize);
	return elfPointer<const ElfW(Shdr)>(elf, offset);
}

/**
 * \brief Retrieve address and size of a symbol from an mmap'ed ELF file
 * \param[in] elf Address and size of mmap'ed ELF file
 * \param[in] symbol Symbol name
 *
 * \return The memory region storing the symbol on success, or an empty span
 * otherwise
 */
Span<const uint8_t> elfLoadSymbol(Span<const uint8_t> elf, const char *symbol)
{
	const ElfW(Ehdr) *eHdr = elfPointer<const ElfW(Ehdr)>(elf, 0);
	if (!eHdr)
		return {};

	const ElfW(Shdr) *sHdr = elfSection(elf, eHdr, eHdr->e_shstrndx);
	if (!sHdr)
		return {};
	off_t shnameoff = sHdr->sh_offset;

	/* Locate .dynsym section header. */
	const ElfW(Shdr) *dynsym = nullptr;
	for (unsigned int i = 0; i < eHdr->e_shnum; i++) {
		sHdr = elfSection(elf, eHdr, i);
		if (!sHdr)
			return {};

		off_t offset = shnameoff + sHdr->sh_name;
		const char *name = elfPointer<const char[8]>(elf, offset);
		if (!name)
			return {};

		if (sHdr->sh_type == SHT_DYNSYM && !strcmp(name, ".dynsym")) {
			dynsym = sHdr;
			break;
		}
	}

	if (dynsym == nullptr) {
		LOG(IPAModule, Error) << "ELF has no .dynsym section";
		return {};
	}

	sHdr = elfSection(elf, eHdr, dynsym->sh_link);
	if (!sHdr)
		return {};
	off_t dynsym_nameoff = sHdr->sh_offset;

	/* Locate symbol in the .dynsym section. */
	const ElfW(Sym) *targetSymbol = nullptr;
	unsigned int dynsym_num = dynsym->sh_size / dynsym->sh_entsize;
	for (unsigned int i = 0; i < dynsym_num; i++) {
		off_t offset = dynsym->sh_offset + dynsym->sh_entsize * i;
		const ElfW(Sym) *sym = elfPointer<const ElfW(Sym)>(elf, offset);
		if (!sym)
			return {};

		offset = dynsym_nameoff + sym->st_name;
		const char *name = elfPointer<const char>(elf, offset,
							  strlen(symbol) + 1);
		if (!name)
			return {};

		if (!strcmp(name, symbol) &&
		    sym->st_info & STB_GLOBAL) {
			targetSymbol = sym;
			break;
		}
	}

	if (targetSymbol == nullptr) {
		LOG(IPAModule, Error) << "Symbol " << symbol << " not found";
		return {};
	}

	/* Locate and return data of symbol. */
	sHdr = elfSection(elf, eHdr, targetSymbol->st_shndx);
	if (!sHdr)
		return {};
	off_t offset = sHdr->sh_offset + (targetSymbol->st_value - sHdr->sh_addr);
	const uint8_t *data = elfPointer<const uint8_t>(elf, offset,
							targetSymbol->st_size);
	if (!data)
		return {};

	return { data, targetSymbol->st_size };
}

} /* namespace */

/**
 * \def IPA_MODULE_API_VERSION
 * \brief The IPA module API version
 *
 * This version number specifies the version for the layout of
 * struct IPAModuleInfo. The IPA module shall use this macro to
 * set its moduleAPIVersion field.
 *
 * \sa IPAModuleInfo::moduleAPIVersion
 */

/**
 * \struct IPAModuleInfo
 * \brief Information of an IPA module
 *
 * This structure contains the information of an IPA module. It is loaded,
 * read, and validated before anything else is loaded from the shared object.
 *
 * \var IPAModuleInfo::moduleAPIVersion
 * \brief The IPA module API version that the IPA module implements
 *
 * This version number specifies the version for the layout of
 * struct IPAModuleInfo. The IPA module shall report here the version that
 * it was built for, using the macro IPA_MODULE_API_VERSION.
 *
 * \var IPAModuleInfo::pipelineVersion
 * \brief The pipeline handler version that the IPA module is for
 *
 * \var IPAModuleInfo::pipelineName
 * \brief The name of the pipeline handler that the IPA module is for
 *
 * This name is used to match a pipeline handler with the module.
 *
 * \var IPAModuleInfo::name
 * \brief The name of the IPA module
 *
 * The name may be used to build file system paths to IPA-specific resources.
 * It shall only contain printable characters, and may not contain '/', '*',
 * '?' or '\'. For IPA modules included in libcamera, it shall match the
 * directory of the IPA module in the source tree.
 *
 * \todo Allow user to choose to isolate open source IPAs
 */

/**
 * \var ipaModuleInfo
 * \brief Information of an IPA module
 *
 * An IPA module must export a struct IPAModuleInfo of this name.
 */

/**
 * \class IPAModule
 * \brief Wrapper around IPA module shared object
 */

/**
 * \brief Construct an IPAModule instance
 * \param[in] libPath path to IPA module shared object
 *
 * Loads the IPAModuleInfo from the IPA module shared object at libPath.
 * The IPA module shared object file must be of the same endianness and
 * bitness as libcamera.
 *
 * The caller shall call the isValid() method after constructing an
 * IPAModule instance to verify the validity of the IPAModule.
 */
IPAModule::IPAModule(const std::string &libPath)
	: libPath_(libPath), valid_(false), loaded_(false),
	  dlHandle_(nullptr), ipaCreate_(nullptr)
{
	if (loadIPAModuleInfo() < 0)
		return;

	valid_ = true;
}

IPAModule::~IPAModule()
{
	if (dlHandle_)
		dlclose(dlHandle_);
}

int IPAModule::loadIPAModuleInfo()
{
	File file{ libPath_ };
	if (!file.open(File::ReadOnly)) {
		LOG(IPAModule, Error) << "Failed to open IPA library: "
				      << strerror(-file.error());
		return file.error();
	}

	Span<const uint8_t> data = file.map();
	int ret = elfVerifyIdent(data);
	if (ret) {
		LOG(IPAModule, Error) << "IPA module is not an ELF file";
		return ret;
	}

	Span<const uint8_t> info = elfLoadSymbol(data, "ipaModuleInfo");
	if (info.size() != sizeof(info_)) {
		LOG(IPAModule, Error) << "IPA module has no valid info";
		return -EINVAL;
	}

	memcpy(&info_, info.data(), info.size());

	if (info_.moduleAPIVersion != IPA_MODULE_API_VERSION) {
		LOG(IPAModule, Error) << "IPA module API version mismatch";
		return -EINVAL;
	}

	/* Validate the IPA module name. */
	std::string ipaName = info_.name;
	auto iter = std::find_if_not(ipaName.begin(), ipaName.end(),
				     [](unsigned char c) -> bool {
					     return isprint(c) && c != '/' &&
						    c != '?' && c != '*' &&
						    c != '\\';
				     });
	if (iter != ipaName.end()) {
		LOG(IPAModule, Error)
			<< "Invalid IPA module name '" << ipaName << "'";
		return -EINVAL;
	}

	/* Load the signature. Failures are not fatal. */
	File sign{ libPath_ + ".sign" };
	if (!sign.open(File::ReadOnly)) {
		LOG(IPAModule, Debug)
			<< "IPA module " << libPath_ << " is not signed";
		return 0;
	}

	data = sign.map(0, -1, File::MapPrivate);
	signature_.resize(data.size());
	memcpy(signature_.data(), data.data(), data.size());

	LOG(IPAModule, Debug) << "IPA module " << libPath_ << " is signed";

	return 0;
}

/**
 * \brief Check if the IPAModule instance is valid
 *
 * An IPAModule instance is valid if the IPA module shared object exists and
 * the IPA module information it contains was successfully retrieved and
 * validated.
 *
 * \return True if the IPAModule is valid, false otherwise
 */
bool IPAModule::isValid() const
{
	return valid_;
}

/**
 * \brief Retrieve the IPA module information
 *
 * The content of the IPA module information is loaded from the module,
 * and is valid only if the module is valid (as returned by isValid()).
 * Calling this function on an invalid module is an error.
 *
 * \return the IPA module information
 */
const struct IPAModuleInfo &IPAModule::info() const
{
	return info_;
}

/**
 * \brief Retrieve the IPA module signature
 *
 * The IPA module signature is stored alongside the IPA module in a file with a
 * '.sign' suffix, and is loaded when the IPAModule instance is created. This
 * function returns the signature without verifying it. If the signature is
 * missing, the returned vector will be empty.
 *
 * \return The IPA module signature
 */
const std::vector<uint8_t> IPAModule::signature() const
{
	return signature_;
}

/**
 * \brief Retrieve the IPA module path
 *
 * The IPA module path is the file name and path of the IPA module shared
 * object from which the IPA module was created.
 *
 * \return The IPA module path
 */
const std::string &IPAModule::path() const
{
	return libPath_;
}

/**
 * \brief Load the IPA implementation factory from the shared object
 *
 * The IPA module shared object implements an ipa_context object to be used
 * by pipeline handlers. This method loads the factory function from the
 * shared object. Later, createContext() can be called to instantiate the
 * ipa_context.
 *
 * This method only needs to be called successfully once, after which
 * createContext() can be called as many times as ipa_context instances are
 * needed.
 *
 * Calling this function on an invalid module (as returned by isValid()) is
 * an error.
 *
 * \return True if load was successful, or already loaded, and false otherwise
 */
bool IPAModule::load()
{
	if (!valid_)
		return false;

	if (loaded_)
		return true;

	dlHandle_ = dlopen(libPath_.c_str(), RTLD_LAZY);
	if (!dlHandle_) {
		LOG(IPAModule, Error)
			<< "Failed to open IPA module shared object: "
			<< dlerror();
		return false;
	}

	void *symbol = dlsym(dlHandle_, "ipaCreate");
	if (!symbol) {
		LOG(IPAModule, Error)
			<< "Failed to load ipaCreate() from IPA module shared object: "
			<< dlerror();
		dlclose(dlHandle_);
		dlHandle_ = nullptr;
		return false;
	}

	ipaCreate_ = reinterpret_cast<IPAIntfFactory>(symbol);

	loaded_ = true;

	return true;
}

/**
 * \brief Instantiate an IPA context
 *
 * After loading the IPA module with load(), this method creates an instance of
 * the IPA module context. Ownership of the context is passed to the caller, and
 * the context shall be destroyed by calling the \ref ipa_context_ops::destroy
 * "ipa_context::ops::destroy()" function.
 *
 * Calling this function on a module that has not yet been loaded, or an
 * invalid module (as returned by load() and isValid(), respectively) is
 * an error.
 *
 * \return The IPA context on success, or nullptr on error
 */