Path: blob/main/contrib/expat/lib/random_getrandom.c
213651 views
/*1__ __ _2___\ \/ /_ __ __ _| |_3/ _ \\ /| '_ \ / _` | __|4| __// \| |_) | (_| | |_5\___/_/\_\ .__/ \__,_|\__|6|_| XML parser78Copyright (c) 2017-2026 Sebastian Pipping <[email protected]>9Copyright (c) 2017 Chanho Park <[email protected]>10Copyright (c) 2022 Sean McBride <[email protected]>11Copyright (c) 2026 Matthew Fernandez <[email protected]>12Licensed under the MIT license:1314Permission is hereby granted, free of charge, to any person obtaining15a copy of this software and associated documentation files (the16"Software"), to deal in the Software without restriction, including17without limitation the rights to use, copy, modify, merge, publish,18distribute, sublicense, and/or sell copies of the Software, and to permit19persons to whom the Software is furnished to do so, subject to the20following conditions:2122The above copyright notice and this permission notice shall be included23in all copies or substantial portions of the Software.2425THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,26EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF27MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN28NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,29DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR30OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE31USE OR OTHER DEALINGS IN THE SOFTWARE.32*/3334#include "random_getrandom.h"3536#include "expat_config.h" // for HAVE_GETRANDOM, HAVE_SYSCALL_GETRANDOM3738#if defined(HAVE_GETRANDOM)39# include <sys/random.h> /* getrandom */40#endif4142#if defined(HAVE_SYSCALL_GETRANDOM)43# if ! defined(_GNU_SOURCE)44# define _GNU_SOURCE 1 /* syscall prototype */45# endif46# include <unistd.h> /* syscall */47# include <sys/syscall.h> /* SYS_getrandom */48#endif // defined(HAVE_SYSCALL_GETRANDOM)4950#if ! defined(GRND_NONBLOCK)51# define GRND_NONBLOCK 0x000152#endif /* defined(GRND_NONBLOCK) */5354#include <assert.h>55#include <errno.h>56#include <limits.h> // for INT_MAX5758/* Obtain entropy on Linux 3.17+ */59bool60writeRandomBytes_getrandom_nonblock(void *target, size_t count) {61int success = false; /* full count bytes written? */62size_t bytesWrittenTotal = 0;63const unsigned int getrandomFlags = GRND_NONBLOCK;6465do {66void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);67const size_t bytesToWrite = count - bytesWrittenTotal;6869assert(bytesToWrite <= INT_MAX);7071errno = 0;7273const int bytesWrittenMore =74#if defined(HAVE_GETRANDOM)75(int)getrandom(currentTarget, bytesToWrite, getrandomFlags);76#else77(int)syscall(SYS_getrandom, currentTarget, bytesToWrite,78getrandomFlags);79#endif8081if (bytesWrittenMore > 0) {82bytesWrittenTotal += bytesWrittenMore;83if (bytesWrittenTotal >= count)84success = true;85}86} while (! success && (errno == EINTR));8788return success;89}909192