code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
#ifndef HEADER_CURL_TOOL_LIBINFO_H
#define HEADER_CURL_TOOL_LIBINFO_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
/* global variable declarations, for libcurl run-time info */
extern curl_version_info_data *curlinfo;
extern long built_in_protos;
CURLcode get_libcurl_info(void);
#endif /* HEADER_CURL_TOOL_LIBINFO_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_libinfo.h | C | apache-2.0 | 1,329 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#include <sys/stat.h>
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef USE_NSS
#include <nspr.h>
#include <plarenas.h>
#endif
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_cfgable.h"
#include "tool_convert.h"
#include "tool_doswin.h"
#include "tool_msgs.h"
#include "tool_operate.h"
#include "tool_panykey.h"
#include "tool_vms.h"
#include "tool_main.h"
#include "tool_libinfo.h"
/*
* This is low-level hard-hacking memory leak tracking and similar. Using
* the library level code from this client-side is ugly, but we do this
* anyway for convenience.
*/
#include "memdebug.h" /* keep this as LAST include */
#ifdef __VMS
/*
* vms_show is a global variable, used in main() as parameter for
* function vms_special_exit() to allow proper curl tool exiting.
* Its value may be set in other tool_*.c source files thanks to
* forward declaration present in tool_vms.h
*/
int vms_show = 0;
#endif
#ifdef __MINGW32__
/*
* There seems to be no way to escape "*" in command-line arguments with MinGW
* when command-line argument globbing is enabled under the MSYS shell, so turn
* it off.
*/
int _CRT_glob = 0;
#endif /* __MINGW32__ */
/* if we build a static library for unit tests, there is no main() function */
#ifndef UNITTESTS
/*
* Ensure that file descriptors 0, 1 and 2 (stdin, stdout, stderr) are
* open before starting to run. Otherwise, the first three network
* sockets opened by curl could be used for input sources, downloaded data
* or error logs as they will effectively be stdin, stdout and/or stderr.
*/
static void main_checkfds(void)
{
#ifdef HAVE_PIPE
int fd[2] = { STDIN_FILENO, STDIN_FILENO };
while(fd[0] == STDIN_FILENO ||
fd[0] == STDOUT_FILENO ||
fd[0] == STDERR_FILENO ||
fd[1] == STDIN_FILENO ||
fd[1] == STDOUT_FILENO ||
fd[1] == STDERR_FILENO)
if(pipe(fd) < 0)
return; /* Out of handles. This isn't really a big problem now, but
will be when we try to create a socket later. */
close(fd[0]);
close(fd[1]);
#endif
}
#ifdef CURLDEBUG
static void memory_tracking_init(void)
{
char *env;
/* if CURL_MEMDEBUG is set, this starts memory tracking message logging */
env = curlx_getenv("CURL_MEMDEBUG");
if(env) {
/* use the value as file name */
char fname[CURL_MT_LOGFNAME_BUFSIZE];
if(strlen(env) >= CURL_MT_LOGFNAME_BUFSIZE)
env[CURL_MT_LOGFNAME_BUFSIZE-1] = '\0';
strcpy(fname, env);
curl_free(env);
curl_dbg_memdebug(fname);
/* this weird stuff here is to make curl_free() get called
before curl_memdebug() as otherwise memory tracking will
log a free() without an alloc! */
}
/* if CURL_MEMLIMIT is set, this enables fail-on-alloc-number-N feature */
env = curlx_getenv("CURL_MEMLIMIT");
if(env) {
char *endptr;
long num = strtol(env, &endptr, 10);
if((endptr != env) && (endptr == env + strlen(env)) && (num > 0))
curl_dbg_memlimit(num);
curl_free(env);
}
}
#else
# define memory_tracking_init() Curl_nop_stmt
#endif
/*
* This is the main global constructor for the app. Call this before
* _any_ libcurl usage. If this fails, *NO* libcurl functions may be
* used, or havoc may be the result.
*/
static CURLcode main_init(struct GlobalConfig *config)
{
CURLcode result = CURLE_OK;
#if defined(__DJGPP__) || defined(__GO32__)
/* stop stat() wasting time */
_djstat_flags |= _STAT_INODE | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
#endif
/* Initialise the global config */
config->showerror = -1; /* Will show errors */
config->errors = stderr; /* Default errors to stderr */
config->styled_output = TRUE; /* enable detection */
/* Allocate the initial operate config */
config->first = config->last = malloc(sizeof(struct OperationConfig));
if(config->first) {
/* Perform the libcurl initialization */
result = curl_global_init(CURL_GLOBAL_DEFAULT);
if(!result) {
/* Get information about libcurl */
result = get_libcurl_info();
if(!result) {
/* Get a curl handle to use for all forthcoming curl transfers */
config->easy = curl_easy_init();
if(config->easy) {
/* Initialise the config */
config_init(config->first);
config->first->easy = config->easy;
config->first->global = config;
}
else {
helpf(stderr, "error initializing curl easy handle\n");
result = CURLE_FAILED_INIT;
free(config->first);
}
}
else {
helpf(stderr, "error retrieving curl library information\n");
free(config->first);
}
}
else {
helpf(stderr, "error initializing curl library\n");
free(config->first);
}
}
else {
helpf(stderr, "error initializing curl\n");
result = CURLE_FAILED_INIT;
}
return result;
}
static void free_globalconfig(struct GlobalConfig *config)
{
Curl_safefree(config->trace_dump);
if(config->errors_fopened && config->errors)
fclose(config->errors);
config->errors = NULL;
if(config->trace_fopened && config->trace_stream)
fclose(config->trace_stream);
config->trace_stream = NULL;
Curl_safefree(config->libcurl);
}
/*
* This is the main global destructor for the app. Call this after
* _all_ libcurl usage is done.
*/
static void main_free(struct GlobalConfig *config)
{
/* Cleanup the easy handle */
curl_easy_cleanup(config->easy);
config->easy = NULL;
/* Main cleanup */
curl_global_cleanup();
convert_cleanup();
metalink_cleanup();
#ifdef USE_NSS
if(PR_Initialized()) {
/* prevent valgrind from reporting still reachable mem from NSRP arenas */
PL_ArenaFinish();
/* prevent valgrind from reporting possibly lost memory (fd cache, ...) */
PR_Cleanup();
}
#endif
free_globalconfig(config);
/* Free the config structures */
config_free(config->last);
config->first = NULL;
config->last = NULL;
}
#ifdef WIN32
/* TerminalSettings for Windows */
static struct TerminalSettings {
HANDLE hStdOut;
DWORD dwOutputMode;
} TerminalSettings;
static void configure_terminal(void)
{
/*
* If we're running Windows, enable VT output.
* Note: VT mode flag can be set on any version of Windows, but VT
* processing only performed on Win10 >= Creators Update)
*/
/* Define the VT flags in case we're building with an older SDK */
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
memset(&TerminalSettings, 0, sizeof(TerminalSettings));
/* Enable VT output */
TerminalSettings.hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if((TerminalSettings.hStdOut != INVALID_HANDLE_VALUE)
&& (GetConsoleMode(TerminalSettings.hStdOut,
&TerminalSettings.dwOutputMode))) {
SetConsoleMode(TerminalSettings.hStdOut,
TerminalSettings.dwOutputMode
| ENABLE_VIRTUAL_TERMINAL_PROCESSING);
}
}
#else
#define configure_terminal()
#endif
static void restore_terminal(void)
{
#ifdef WIN32
/* Restore Console output mode and codepage to whatever they were
* when Curl started */
SetConsoleMode(TerminalSettings.hStdOut, TerminalSettings.dwOutputMode);
#endif
}
/*
** curl tool main function.
*/
int main(int argc, char *argv[])
{
CURLcode result = CURLE_OK;
struct GlobalConfig global;
memset(&global, 0, sizeof(global));
/* Perform any platform-specific terminal configuration */
configure_terminal();
main_checkfds();
#if defined(HAVE_SIGNAL) && defined(SIGPIPE)
(void)signal(SIGPIPE, SIG_IGN);
#endif
/* Initialize memory tracking */
memory_tracking_init();
/* Initialize the curl library - do not call any libcurl functions before
this point */
result = main_init(&global);
#ifdef WIN32
/* Undocumented diagnostic option to list the full paths of all loaded
modules, regardless of whether or not initialization succeeded. */
if(argc == 2 && !strcmp(argv[1], "--dump-module-paths")) {
struct curl_slist *item, *head = GetLoadedModulePaths();
for(item = head; item; item = item->next) {
printf("%s\n", item->data);
}
curl_slist_free_all(head);
if(!result)
main_free(&global);
}
else
#endif /* WIN32 */
if(!result) {
/* Start our curl operation */
result = operate(&global, argc, argv);
#ifdef __SYMBIAN32__
if(global.showerror)
tool_pressanykey();
#endif
/* Perform the main cleanup */
main_free(&global);
}
/* Return the terminal to its original state */
restore_terminal();
#ifdef __NOVELL_LIBC__
if(getenv("_IN_NETWARE_BASH_") == NULL)
tool_pressanykey();
#endif
#ifdef __VMS
vms_special_exit(result, vms_show);
#else
return (int)result;
#endif
}
#endif /* ndef UNITTESTS */
| YifuLiu/AliOS-Things | components/curl/src/tool_main.c | C | apache-2.0 | 9,900 |
#ifndef HEADER_CURL_TOOL_MAIN_H
#define HEADER_CURL_TOOL_MAIN_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#define DEFAULT_MAXREDIRS 50L
#define RETRY_SLEEP_DEFAULT 1000L /* ms */
#define RETRY_SLEEP_MAX 600000L /* ms == 10 minutes */
#ifndef STDIN_FILENO
# define STDIN_FILENO fileno(stdin)
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO fileno(stdout)
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO fileno(stderr)
#endif
#endif /* HEADER_CURL_TOOL_MAIN_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_main.h | C | apache-2.0 | 1,496 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#ifdef USE_METALINK
#include <sys/stat.h>
#include <stdlib.h>
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif
#undef HAVE_NSS_CONTEXT
#ifdef USE_OPENSSL
# include <openssl/md5.h>
# include <openssl/sha.h>
#elif defined(USE_GNUTLS_NETTLE)
# include <nettle/md5.h>
# include <nettle/sha.h>
# define MD5_CTX struct md5_ctx
# define SHA_CTX struct sha1_ctx
# define SHA256_CTX struct sha256_ctx
#elif defined(USE_GNUTLS)
# include <gcrypt.h>
# define MD5_CTX gcry_md_hd_t
# define SHA_CTX gcry_md_hd_t
# define SHA256_CTX gcry_md_hd_t
#elif defined(USE_NSS)
# include <nss.h>
# include <pk11pub.h>
# define MD5_CTX void *
# define SHA_CTX void *
# define SHA256_CTX void *
# define HAVE_NSS_CONTEXT
static NSSInitContext *nss_context;
#elif defined(USE_POLARSSL)
# include <polarssl/md5.h>
# include <polarssl/sha1.h>
# include <polarssl/sha256.h>
# define MD5_CTX md5_context
# define SHA_CTX sha1_context
# define SHA256_CTX sha256_context
#elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \
(__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040)) || \
(defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \
(__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000))
/* For Apple operating systems: CommonCrypto has the functions we need.
The library's headers are even backward-compatible with OpenSSL's
headers as long as we define COMMON_DIGEST_FOR_OPENSSL first.
These functions are available on Tiger and later, as well as iOS 2.0
and later. If you're building for an older cat, well, sorry. */
# define COMMON_DIGEST_FOR_OPENSSL
# include <CommonCrypto/CommonDigest.h>
#elif defined(WIN32)
/* For Windows: If no other crypto library is provided, we fallback
to the hash functions provided within the Microsoft Windows CryptoAPI */
# include <wincrypt.h>
/* Custom structure in order to store the required provider and hash handle */
struct win32_crypto_hash {
HCRYPTPROV hCryptProv;
HCRYPTHASH hHash;
};
/* Custom Microsoft AES Cryptographic Provider defines required for MinGW */
# ifndef ALG_SID_SHA_256
# define ALG_SID_SHA_256 12
# endif
# ifndef CALG_SHA_256
# define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
# endif
# define MD5_CTX struct win32_crypto_hash
# define SHA_CTX struct win32_crypto_hash
# define SHA256_CTX struct win32_crypto_hash
#else
# error "Can't compile METALINK support without a crypto library."
#endif
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_getparam.h"
#include "tool_paramhlp.h"
#include "tool_cfgable.h"
#include "tool_metalink.h"
#include "tool_msgs.h"
#include "memdebug.h" /* keep this as LAST include */
/* Copied from tool_getparam.c */
#define GetStr(str,val) do { \
if(*(str)) { \
free(*(str)); \
*(str) = NULL; \
} \
if((val)) \
*(str) = strdup((val)); \
if(!(val)) \
return PARAM_NO_MEM; \
} WHILE_FALSE
#if defined(USE_OPENSSL)
/* Functions are already defined */
#elif defined(USE_GNUTLS_NETTLE)
static int MD5_Init(MD5_CTX *ctx)
{
md5_init(ctx);
return 1;
}
static void MD5_Update(MD5_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
md5_update(ctx, inputLen, input);
}
static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx)
{
md5_digest(ctx, 16, digest);
}
static int SHA1_Init(SHA_CTX *ctx)
{
sha1_init(ctx);
return 1;
}
static void SHA1_Update(SHA_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
sha1_update(ctx, inputLen, input);
}
static void SHA1_Final(unsigned char digest[20], SHA_CTX *ctx)
{
sha1_digest(ctx, 20, digest);
}
static int SHA256_Init(SHA256_CTX *ctx)
{
sha256_init(ctx);
return 1;
}
static void SHA256_Update(SHA256_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
sha256_update(ctx, inputLen, input);
}
static void SHA256_Final(unsigned char digest[32], SHA256_CTX *ctx)
{
sha256_digest(ctx, 32, digest);
}
#elif defined(USE_GNUTLS)
static int MD5_Init(MD5_CTX *ctx)
{
gcry_md_open(ctx, GCRY_MD_MD5, 0);
return 1;
}
static void MD5_Update(MD5_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
gcry_md_write(*ctx, input, inputLen);
}
static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx)
{
memcpy(digest, gcry_md_read(*ctx, 0), 16);
gcry_md_close(*ctx);
}
static int SHA1_Init(SHA_CTX *ctx)
{
gcry_md_open(ctx, GCRY_MD_SHA1, 0);
return 1;
}
static void SHA1_Update(SHA_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
gcry_md_write(*ctx, input, inputLen);
}
static void SHA1_Final(unsigned char digest[20], SHA_CTX *ctx)
{
memcpy(digest, gcry_md_read(*ctx, 0), 20);
gcry_md_close(*ctx);
}
static int SHA256_Init(SHA256_CTX *ctx)
{
gcry_md_open(ctx, GCRY_MD_SHA256, 0);
return 1;
}
static void SHA256_Update(SHA256_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
gcry_md_write(*ctx, input, inputLen);
}
static void SHA256_Final(unsigned char digest[32], SHA256_CTX *ctx)
{
memcpy(digest, gcry_md_read(*ctx, 0), 32);
gcry_md_close(*ctx);
}
#elif defined(USE_NSS)
static int nss_hash_init(void **pctx, SECOidTag hash_alg)
{
PK11Context *ctx;
/* we have to initialize NSS if not initialized already */
if(!NSS_IsInitialized() && !nss_context) {
static NSSInitParameters params;
params.length = sizeof(params);
nss_context = NSS_InitContext("", "", "", "", ¶ms, NSS_INIT_READONLY
| NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN
| NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
}
ctx = PK11_CreateDigestContext(hash_alg);
if(!ctx)
return /* failure */ 0;
if(PK11_DigestBegin(ctx) != SECSuccess) {
PK11_DestroyContext(ctx, PR_TRUE);
return /* failure */ 0;
}
*pctx = ctx;
return /* success */ 1;
}
static void nss_hash_final(void **pctx, unsigned char *out, unsigned int len)
{
PK11Context *ctx = *pctx;
unsigned int outlen;
PK11_DigestFinal(ctx, out, &outlen, len);
PK11_DestroyContext(ctx, PR_TRUE);
}
static int MD5_Init(MD5_CTX *pctx)
{
return nss_hash_init(pctx, SEC_OID_MD5);
}
static void MD5_Update(MD5_CTX *pctx,
const unsigned char *input,
unsigned int input_len)
{
PK11_DigestOp(*pctx, input, input_len);
}
static void MD5_Final(unsigned char digest[16], MD5_CTX *pctx)
{
nss_hash_final(pctx, digest, 16);
}
static int SHA1_Init(SHA_CTX *pctx)
{
return nss_hash_init(pctx, SEC_OID_SHA1);
}
static void SHA1_Update(SHA_CTX *pctx,
const unsigned char *input,
unsigned int input_len)
{
PK11_DigestOp(*pctx, input, input_len);
}
static void SHA1_Final(unsigned char digest[20], SHA_CTX *pctx)
{
nss_hash_final(pctx, digest, 20);
}
static int SHA256_Init(SHA256_CTX *pctx)
{
return nss_hash_init(pctx, SEC_OID_SHA256);
}
static void SHA256_Update(SHA256_CTX *pctx,
const unsigned char *input,
unsigned int input_len)
{
PK11_DigestOp(*pctx, input, input_len);
}
static void SHA256_Final(unsigned char digest[32], SHA256_CTX *pctx)
{
nss_hash_final(pctx, digest, 32);
}
#elif defined(USE_POLARSSL)
static int MD5_Init(MD5_CTX *ctx)
{
md5_starts(ctx);
return 1;
}
static void MD5_Update(MD5_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
md5_update(ctx, input, inputLen);
}
static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx)
{
md5_finish(ctx, digest);
}
static int SHA1_Init(SHA_CTX *ctx)
{
sha1_starts(ctx);
return 1;
}
static void SHA1_Update(SHA_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
sha1_update(ctx, input, inputLen);
}
static void SHA1_Final(unsigned char digest[20], SHA_CTX *ctx)
{
sha1_finish(ctx, digest);
}
static int SHA256_Init(SHA256_CTX *ctx)
{
sha256_starts(ctx, 0); /* 0 = sha256 */
return 1;
}
static void SHA256_Update(SHA256_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
sha256_update(ctx, input, inputLen);
}
static void SHA256_Final(unsigned char digest[32], SHA256_CTX *ctx)
{
sha256_finish(ctx, digest);
}
#elif defined(WIN32)
static void win32_crypto_final(struct win32_crypto_hash *ctx,
unsigned char *digest,
unsigned int digestLen)
{
unsigned long length;
CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0);
if(length == digestLen)
CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0);
if(ctx->hHash)
CryptDestroyHash(ctx->hHash);
if(ctx->hCryptProv)
CryptReleaseContext(ctx->hCryptProv, 0);
}
static int MD5_Init(MD5_CTX *ctx)
{
if(CryptAcquireContext(&ctx->hCryptProv, NULL, NULL,
PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
CryptCreateHash(ctx->hCryptProv, CALG_MD5, 0, 0, &ctx->hHash);
}
return 1;
}
static void MD5_Update(MD5_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0);
}
static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx)
{
win32_crypto_final(ctx, digest, 16);
}
static int SHA1_Init(SHA_CTX *ctx)
{
if(CryptAcquireContext(&ctx->hCryptProv, NULL, NULL,
PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
CryptCreateHash(ctx->hCryptProv, CALG_SHA1, 0, 0, &ctx->hHash);
}
return 1;
}
static void SHA1_Update(SHA_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0);
}
static void SHA1_Final(unsigned char digest[20], SHA_CTX *ctx)
{
win32_crypto_final(ctx, digest, 20);
}
static int SHA256_Init(SHA256_CTX *ctx)
{
if(CryptAcquireContext(&ctx->hCryptProv, NULL, NULL,
PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
CryptCreateHash(ctx->hCryptProv, CALG_SHA_256, 0, 0, &ctx->hHash);
}
return 1;
}
static void SHA256_Update(SHA256_CTX *ctx,
const unsigned char *input,
unsigned int inputLen)
{
CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0);
}
static void SHA256_Final(unsigned char digest[32], SHA256_CTX *ctx)
{
win32_crypto_final(ctx, digest, 32);
}
#endif /* CRYPTO LIBS */
const digest_params MD5_DIGEST_PARAMS[] = {
{
CURLX_FUNCTION_CAST(Curl_digest_init_func, MD5_Init),
CURLX_FUNCTION_CAST(Curl_digest_update_func, MD5_Update),
CURLX_FUNCTION_CAST(Curl_digest_final_func, MD5_Final),
sizeof(MD5_CTX),
16
}
};
const digest_params SHA1_DIGEST_PARAMS[] = {
{
CURLX_FUNCTION_CAST(Curl_digest_init_func, SHA1_Init),
CURLX_FUNCTION_CAST(Curl_digest_update_func, SHA1_Update),
CURLX_FUNCTION_CAST(Curl_digest_final_func, SHA1_Final),
sizeof(SHA_CTX),
20
}
};
const digest_params SHA256_DIGEST_PARAMS[] = {
{
CURLX_FUNCTION_CAST(Curl_digest_init_func, SHA256_Init),
CURLX_FUNCTION_CAST(Curl_digest_update_func, SHA256_Update),
CURLX_FUNCTION_CAST(Curl_digest_final_func, SHA256_Final),
sizeof(SHA256_CTX),
32
}
};
static const metalink_digest_def SHA256_DIGEST_DEF[] = {
{"sha-256", SHA256_DIGEST_PARAMS}
};
static const metalink_digest_def SHA1_DIGEST_DEF[] = {
{"sha-1", SHA1_DIGEST_PARAMS}
};
static const metalink_digest_def MD5_DIGEST_DEF[] = {
{"md5", MD5_DIGEST_PARAMS}
};
/*
* The alias of supported hash functions in the order by preference
* (basically stronger hash comes first). We included "sha-256" and
* "sha256". The former is the name defined in the IANA registry named
* "Hash Function Textual Names". The latter is widely (and
* historically) used in Metalink version 3.
*/
static const metalink_digest_alias digest_aliases[] = {
{"sha-256", SHA256_DIGEST_DEF},
{"sha256", SHA256_DIGEST_DEF},
{"sha-1", SHA1_DIGEST_DEF},
{"sha1", SHA1_DIGEST_DEF},
{"md5", MD5_DIGEST_DEF},
{NULL, NULL}
};
digest_context *Curl_digest_init(const digest_params *dparams)
{
digest_context *ctxt;
/* Create digest context */
ctxt = malloc(sizeof(*ctxt));
if(!ctxt)
return ctxt;
ctxt->digest_hashctx = malloc(dparams->digest_ctxtsize);
if(!ctxt->digest_hashctx) {
free(ctxt);
return NULL;
}
ctxt->digest_hash = dparams;
if(dparams->digest_init(ctxt->digest_hashctx) != 1) {
free(ctxt->digest_hashctx);
free(ctxt);
return NULL;
}
return ctxt;
}
int Curl_digest_update(digest_context *context,
const unsigned char *data,
unsigned int len)
{
(*context->digest_hash->digest_update)(context->digest_hashctx, data, len);
return 0;
}
int Curl_digest_final(digest_context *context, unsigned char *result)
{
if(result)
(*context->digest_hash->digest_final)(result, context->digest_hashctx);
free(context->digest_hashctx);
free(context);
return 0;
}
static unsigned char hex_to_uint(const char *s)
{
char buf[3];
unsigned long val;
buf[0] = s[0];
buf[1] = s[1];
buf[2] = 0;
val = strtoul(buf, NULL, 16);
return (unsigned char)(val&0xff);
}
/*
* Check checksum of file denoted by filename. The expected hash value
* is given in hex_hash which is hex-encoded string.
*
* This function returns 1 if it succeeds or one of the following
* integers:
*
* 0:
* Checksum didn't match.
* -1:
* Could not open file; or could not read data from file.
* -2:
* Hash algorithm not available.
*/
static int check_hash(const char *filename,
const metalink_digest_def *digest_def,
const unsigned char *digest, FILE *error)
{
unsigned char *result;
digest_context *dctx;
int check_ok, flags, fd;
flags = O_RDONLY;
#ifdef O_BINARY
/* O_BINARY is required in order to avoid binary EOF in text mode */
flags |= O_BINARY;
#endif
fd = open(filename, flags);
if(fd == -1) {
fprintf(error, "Metalink: validating (%s) [%s] FAILED (%s)\n", filename,
digest_def->hash_name, strerror(errno));
return -1;
}
dctx = Curl_digest_init(digest_def->dparams);
if(!dctx) {
fprintf(error, "Metalink: validating (%s) [%s] FAILED (%s)\n", filename,
digest_def->hash_name, "failed to initialize hash algorithm");
close(fd);
return -2;
}
result = malloc(digest_def->dparams->digest_resultlen);
if(!result) {
close(fd);
Curl_digest_final(dctx, NULL);
return -1;
}
while(1) {
unsigned char buf[4096];
ssize_t len = read(fd, buf, sizeof(buf));
if(len == 0) {
break;
}
else if(len == -1) {
fprintf(error, "Metalink: validating (%s) [%s] FAILED (%s)\n", filename,
digest_def->hash_name, strerror(errno));
Curl_digest_final(dctx, result);
close(fd);
return -1;
}
Curl_digest_update(dctx, buf, (unsigned int)len);
}
Curl_digest_final(dctx, result);
check_ok = memcmp(result, digest,
digest_def->dparams->digest_resultlen) == 0;
/* sha*sum style verdict output */
if(check_ok)
fprintf(error, "Metalink: validating (%s) [%s] OK\n", filename,
digest_def->hash_name);
else
fprintf(error, "Metalink: validating (%s) [%s] FAILED (digest mismatch)\n",
filename, digest_def->hash_name);
free(result);
close(fd);
return check_ok;
}
int metalink_check_hash(struct GlobalConfig *config,
metalinkfile *mlfile,
const char *filename)
{
int rv;
fprintf(config->errors, "Metalink: validating (%s)...\n", filename);
if(mlfile->checksum == NULL) {
fprintf(config->errors,
"Metalink: validating (%s) FAILED (digest missing)\n", filename);
return -2;
}
rv = check_hash(filename, mlfile->checksum->digest_def,
mlfile->checksum->digest, config->errors);
return rv;
}
static metalink_checksum *new_metalink_checksum_from_hex_digest
(const metalink_digest_def *digest_def, const char *hex_digest)
{
metalink_checksum *chksum;
unsigned char *digest;
size_t i;
size_t len = strlen(hex_digest);
digest = malloc(len/2);
if(!digest)
return 0;
for(i = 0; i < len; i += 2) {
digest[i/2] = hex_to_uint(hex_digest + i);
}
chksum = malloc(sizeof(metalink_checksum));
if(chksum) {
chksum->digest_def = digest_def;
chksum->digest = digest;
}
else
free(digest);
return chksum;
}
static metalink_resource *new_metalink_resource(const char *url)
{
metalink_resource *res;
res = malloc(sizeof(metalink_resource));
if(res) {
res->next = NULL;
res->url = strdup(url);
if(!res->url) {
free(res);
return NULL;
}
}
return res;
}
/* Returns nonzero if hex_digest is properly formatted; that is each
letter is in [0-9A-Za-z] and the length of the string equals to the
result length of digest * 2. */
static int check_hex_digest(const char *hex_digest,
const metalink_digest_def *digest_def)
{
size_t i;
for(i = 0; hex_digest[i]; ++i) {
char c = hex_digest[i];
if(!(('0' <= c && c <= '9') || ('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z'))) {
return 0;
}
}
return digest_def->dparams->digest_resultlen * 2 == i;
}
static metalinkfile *new_metalinkfile(metalink_file_t *fileinfo)
{
metalinkfile *f;
f = (metalinkfile*)malloc(sizeof(metalinkfile));
if(!f)
return NULL;
f->next = NULL;
f->filename = strdup(fileinfo->name);
if(!f->filename) {
free(f);
return NULL;
}
f->checksum = NULL;
f->resource = NULL;
if(fileinfo->checksums) {
const metalink_digest_alias *digest_alias;
for(digest_alias = digest_aliases; digest_alias->alias_name;
++digest_alias) {
metalink_checksum_t **p;
for(p = fileinfo->checksums; *p; ++p) {
if(curl_strequal(digest_alias->alias_name, (*p)->type) &&
check_hex_digest((*p)->hash, digest_alias->digest_def)) {
f->checksum =
new_metalink_checksum_from_hex_digest(digest_alias->digest_def,
(*p)->hash);
break;
}
}
if(f->checksum) {
break;
}
}
}
if(fileinfo->resources) {
metalink_resource_t **p;
metalink_resource root, *tail;
root.next = NULL;
tail = &root;
for(p = fileinfo->resources; *p; ++p) {
metalink_resource *res;
/* Filter by type if it is non-NULL. In Metalink v3, type
includes the type of the resource. In curl, we are only
interested in HTTP, HTTPS and FTP. In addition to them,
Metalink v3 file may contain bittorrent type URL, which
points to the BitTorrent metainfo file. We ignore it here.
In Metalink v4, type was deprecated and all
fileinfo->resources point to the target file. BitTorrent
metainfo file URL may be appeared in fileinfo->metaurls.
*/
if((*p)->type == NULL ||
curl_strequal((*p)->type, "http") ||
curl_strequal((*p)->type, "https") ||
curl_strequal((*p)->type, "ftp") ||
curl_strequal((*p)->type, "ftps")) {
res = new_metalink_resource((*p)->url);
if(res) {
tail->next = res;
tail = res;
}
else {
tail = root.next;
/* clean up the linked list */
while(tail) {
res = tail->next;
free(tail->url);
free(tail);
tail = res;
}
free(f->filename);
free(f);
return NULL;
}
}
}
f->resource = root.next;
}
return f;
}
int parse_metalink(struct OperationConfig *config, struct OutStruct *outs,
const char *metalink_url)
{
metalink_error_t r;
metalink_t* metalink;
metalink_file_t **files;
bool warnings = FALSE;
/* metlaink_parse_final deletes outs->metalink_parser */
r = metalink_parse_final(outs->metalink_parser, NULL, 0, &metalink);
outs->metalink_parser = NULL;
if(r != 0) {
return -1;
}
if(metalink->files == NULL) {
fprintf(config->global->errors, "Metalink: parsing (%s) WARNING "
"(missing or invalid file name)\n",
metalink_url);
metalink_delete(metalink);
return -1;
}
for(files = metalink->files; *files; ++files) {
struct getout *url;
/* Skip an entry which has no resource. */
if(!(*files)->resources) {
fprintf(config->global->errors, "Metalink: parsing (%s) WARNING "
"(missing or invalid resource)\n",
metalink_url);
continue;
}
if(config->url_get ||
((config->url_get = config->url_list) != NULL)) {
/* there's a node here, if it already is filled-in continue to
find an "empty" node */
while(config->url_get && (config->url_get->flags & GETOUT_URL))
config->url_get = config->url_get->next;
}
/* now there might or might not be an available node to fill in! */
if(config->url_get)
/* existing node */
url = config->url_get;
else
/* there was no free node, create one! */
url = new_getout(config);
if(url) {
metalinkfile *mlfile = new_metalinkfile(*files);
if(!mlfile)
break;
if(!mlfile->checksum) {
warnings = TRUE;
fprintf(config->global->errors,
"Metalink: parsing (%s) WARNING (digest missing)\n",
metalink_url);
}
/* Set name as url */
GetStr(&url->url, mlfile->filename);
/* set flag metalink here */
url->flags |= GETOUT_URL | GETOUT_METALINK;
if(config->metalinkfile_list) {
config->metalinkfile_last->next = mlfile;
config->metalinkfile_last = mlfile;
}
else {
config->metalinkfile_list = config->metalinkfile_last = mlfile;
}
}
}
metalink_delete(metalink);
return (warnings) ? -2 : 0;
}
size_t metalink_write_cb(void *buffer, size_t sz, size_t nmemb,
void *userdata)
{
struct OutStruct *outs = userdata;
struct OperationConfig *config = outs->config;
int rv;
/*
* Once that libcurl has called back tool_write_cb() the returned value
* is checked against the amount that was intended to be written, if
* it does not match then it fails with CURLE_WRITE_ERROR. So at this
* point returning a value different from sz*nmemb indicates failure.
*/
const size_t failure = (sz && nmemb) ? 0 : 1;
if(!config)
return failure;
rv = metalink_parse_update(outs->metalink_parser, buffer, sz * nmemb);
if(rv == 0)
return sz * nmemb;
else {
fprintf(config->global->errors, "Metalink: parsing FAILED\n");
return failure;
}
}
/*
* Returns nonzero if content_type includes mediatype.
*/
static int check_content_type(const char *content_type, const char *media_type)
{
const char *ptr = content_type;
size_t media_type_len = strlen(media_type);
for(; *ptr && (*ptr == ' ' || *ptr == '\t'); ++ptr);
if(!*ptr) {
return 0;
}
return curl_strnequal(ptr, media_type, media_type_len) &&
(*(ptr + media_type_len) == '\0' || *(ptr + media_type_len) == ' ' ||
*(ptr + media_type_len) == '\t' || *(ptr + media_type_len) == ';');
}
int check_metalink_content_type(const char *content_type)
{
return check_content_type(content_type, "application/metalink+xml");
}
int count_next_metalink_resource(metalinkfile *mlfile)
{
int count = 0;
metalink_resource *res;
for(res = mlfile->resource; res; res = res->next, ++count);
return count;
}
static void delete_metalink_checksum(metalink_checksum *chksum)
{
if(chksum == NULL) {
return;
}
Curl_safefree(chksum->digest);
Curl_safefree(chksum);
}
static void delete_metalink_resource(metalink_resource *res)
{
if(res == NULL) {
return;
}
Curl_safefree(res->url);
Curl_safefree(res);
}
static void delete_metalinkfile(metalinkfile *mlfile)
{
metalink_resource *res;
if(mlfile == NULL) {
return;
}
Curl_safefree(mlfile->filename);
delete_metalink_checksum(mlfile->checksum);
for(res = mlfile->resource; res;) {
metalink_resource *next;
next = res->next;
delete_metalink_resource(res);
res = next;
}
Curl_safefree(mlfile);
}
void clean_metalink(struct OperationConfig *config)
{
while(config->metalinkfile_list) {
metalinkfile *mlfile = config->metalinkfile_list;
config->metalinkfile_list = config->metalinkfile_list->next;
delete_metalinkfile(mlfile);
}
config->metalinkfile_last = 0;
}
void metalink_cleanup(void)
{
#ifdef HAVE_NSS_CONTEXT
if(nss_context) {
NSS_ShutdownContext(nss_context);
nss_context = NULL;
}
#endif
}
#endif /* USE_METALINK */
| YifuLiu/AliOS-Things | components/curl/src/tool_metalink.c | C | apache-2.0 | 26,261 |
#ifndef HEADER_CURL_TOOL_METALINK_H
#define HEADER_CURL_TOOL_METALINK_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
struct GlobalConfig;
struct OperationConfig;
/* returns 1 for success, 0 otherwise (we use OpenSSL *_Init fncs directly) */
typedef int (* Curl_digest_init_func)(void *context);
typedef void (* Curl_digest_update_func)(void *context,
const unsigned char *data,
unsigned int len);
typedef void (* Curl_digest_final_func)(unsigned char *result, void *context);
typedef struct {
Curl_digest_init_func digest_init; /* Initialize context procedure */
Curl_digest_update_func digest_update; /* Update context with data */
Curl_digest_final_func digest_final; /* Get final result procedure */
unsigned int digest_ctxtsize; /* Context structure size */
unsigned int digest_resultlen; /* Result length (bytes) */
} digest_params;
typedef struct {
const digest_params *digest_hash; /* Hash function definition */
void *digest_hashctx; /* Hash function context */
} digest_context;
digest_context * Curl_digest_init(const digest_params *dparams);
int Curl_digest_update(digest_context *context,
const unsigned char *data,
unsigned int len);
int Curl_digest_final(digest_context *context, unsigned char *result);
typedef struct {
const char *hash_name;
const digest_params *dparams;
} metalink_digest_def;
typedef struct {
const char *alias_name;
const metalink_digest_def *digest_def;
} metalink_digest_alias;
typedef struct metalink_checksum {
const metalink_digest_def *digest_def;
/* raw digest value, not ascii hex digest */
unsigned char *digest;
} metalink_checksum;
typedef struct metalink_resource {
struct metalink_resource *next;
char *url;
} metalink_resource;
typedef struct metalinkfile {
struct metalinkfile *next;
char *filename;
metalink_checksum *checksum;
metalink_resource *resource;
} metalinkfile;
#ifdef USE_METALINK
/*
* curl requires libmetalink 0.1.0 or newer
*/
#define CURL_REQ_LIBMETALINK_MAJOR 0
#define CURL_REQ_LIBMETALINK_MINOR 1
#define CURL_REQ_LIBMETALINK_PATCH 0
#define CURL_REQ_LIBMETALINK_VERS ((CURL_REQ_LIBMETALINK_MAJOR * 10000) + \
(CURL_REQ_LIBMETALINK_MINOR * 100) + \
CURL_REQ_LIBMETALINK_PATCH)
extern const digest_params MD5_DIGEST_PARAMS[1];
extern const digest_params SHA1_DIGEST_PARAMS[1];
extern const digest_params SHA256_DIGEST_PARAMS[1];
#include <metalink/metalink.h>
/*
* Counts the resource in the metalinkfile.
*/
int count_next_metalink_resource(metalinkfile *mlfile);
void clean_metalink(struct OperationConfig *config);
/*
* Performs final parse operation and extracts information from
* Metalink and creates metalinkfile structs.
*
* This function returns 0 if it succeeds without warnings, or one of
* the following negative error codes:
*
* -1: Parsing failed; or no file is found
* -2: Parsing succeeded with some warnings.
*/
int parse_metalink(struct OperationConfig *config, struct OutStruct *outs,
const char *metalink_url);
/*
* Callback function for CURLOPT_WRITEFUNCTION
*/
size_t metalink_write_cb(void *buffer, size_t sz, size_t nmemb,
void *userdata);
/*
* Returns nonzero if content_type includes "application/metalink+xml"
* media-type. The check is done in case-insensitive manner.
*/
int check_metalink_content_type(const char *content_type);
/*
* Check checksum of file denoted by filename.
*
* This function returns 1 if the checksum matches or one of the
* following integers:
*
* 0:
* Checksum didn't match.
* -1:
* Could not open file; or could not read data from file.
* -2:
* No checksum in Metalink supported, hash algorithm not available, or
* Metalink does not contain checksum.
*/
int metalink_check_hash(struct GlobalConfig *config,
metalinkfile *mlfile,
const char *filename);
/*
* Release resources allocated at global scope.
*/
void metalink_cleanup(void);
#else /* USE_METALINK */
#define count_next_metalink_resource(x) 0
#define clean_metalink(x) (void)x
/* metalink_cleanup() takes no arguments */
#define metalink_cleanup() Curl_nop_stmt
#endif /* USE_METALINK */
#endif /* HEADER_CURL_TOOL_METALINK_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_metalink.h | C | apache-2.0 | 5,482 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2015, 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_cfgable.h"
#include "tool_msgs.h"
#include "memdebug.h" /* keep this as LAST include */
#define WARN_PREFIX "Warning: "
#define NOTE_PREFIX "Note: "
static void voutf(struct GlobalConfig *config,
const char *prefix,
const char *fmt,
va_list ap)
{
size_t width = (79 - strlen(prefix));
if(!config->mute) {
size_t len;
char *ptr;
char *print_buffer;
print_buffer = curlx_mvaprintf(fmt, ap);
if(!print_buffer)
return;
len = strlen(print_buffer);
ptr = print_buffer;
while(len > 0) {
fputs(prefix, config->errors);
if(len > width) {
size_t cut = width-1;
while(!ISSPACE(ptr[cut]) && cut) {
cut--;
}
if(0 == cut)
/* not a single cutting position was found, just cut it at the
max text width then! */
cut = width-1;
(void)fwrite(ptr, cut + 1, 1, config->errors);
fputs("\n", config->errors);
ptr += cut + 1; /* skip the space too */
len -= cut + 1;
}
else {
fputs(ptr, config->errors);
len = 0;
}
}
curl_free(print_buffer);
}
}
/*
* Emit 'note' formatted message on configured 'errors' stream, if verbose was
* selected.
*/
void notef(struct GlobalConfig *config, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if(config->tracetype)
voutf(config, NOTE_PREFIX, fmt, ap);
va_end(ap);
}
/*
* Emit warning formatted message on configured 'errors' stream unless
* mute (--silent) was selected.
*/
void warnf(struct GlobalConfig *config, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
voutf(config, WARN_PREFIX, fmt, ap);
va_end(ap);
}
/*
* Emit help formatted message on given stream.
*/
void helpf(FILE *errors, const char *fmt, ...)
{
if(fmt) {
va_list ap;
va_start(ap, fmt);
fputs("curl: ", errors); /* prefix it */
vfprintf(errors, fmt, ap);
va_end(ap);
}
fprintf(errors, "curl: try 'curl --help' "
#ifdef USE_MANUAL
"or 'curl --manual' "
#endif
"for more information\n");
}
| YifuLiu/AliOS-Things | components/curl/src/tool_msgs.c | C | apache-2.0 | 3,286 |
#ifndef HEADER_CURL_TOOL_MSGS_H
#define HEADER_CURL_TOOL_MSGS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
void warnf(struct GlobalConfig *config, const char *fmt, ...);
void notef(struct GlobalConfig *config, const char *fmt, ...);
void helpf(FILE *errors, const char *fmt, ...);
#endif /* HEADER_CURL_TOOL_MSGS_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_msgs.h | C | apache-2.0 | 1,328 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif
#ifdef HAVE_LOCALE_H
# include <locale.h>
#endif
#ifdef __VMS
# include <fabdef.h>
#endif
#ifdef __AMIGA__
# include <proto/dos.h>
#endif
#include "strcase.h"
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_binmode.h"
#include "tool_cfgable.h"
#include "tool_cb_dbg.h"
#include "tool_cb_hdr.h"
#include "tool_cb_prg.h"
#include "tool_cb_rea.h"
#include "tool_cb_see.h"
#include "tool_cb_wrt.h"
#include "tool_dirhie.h"
#include "tool_doswin.h"
#include "tool_easysrc.h"
#include "tool_filetime.h"
#include "tool_getparam.h"
#include "tool_helpers.h"
#include "tool_homedir.h"
#include "tool_libinfo.h"
#include "tool_main.h"
#include "tool_metalink.h"
#include "tool_msgs.h"
#include "tool_operate.h"
#include "tool_operhlp.h"
#include "tool_paramhlp.h"
#include "tool_parsecfg.h"
#include "tool_setopt.h"
#include "tool_sleep.h"
#include "tool_urlglob.h"
#include "tool_util.h"
#include "tool_writeout.h"
#include "tool_xattr.h"
#include "tool_vms.h"
#include "tool_help.h"
#include "tool_hugehelp.h"
#include "memdebug.h" /* keep this as LAST include */
#ifdef CURLDEBUG
/* libcurl's debug builds provide an extra function */
CURLcode curl_easy_perform_ev(CURL *easy);
#endif
#define CURLseparator "--_curl_--"
#ifndef O_BINARY
/* since O_BINARY as used in bitmasks, setting it to zero makes it usable in
source code but yet it doesn't ruin anything */
# define O_BINARY 0
#endif
#define CURL_CA_CERT_ERRORMSG \
"More details here: https://curl.haxx.se/docs/sslcerts.html\n\n" \
"curl failed to verify the legitimacy of the server and therefore " \
"could not\nestablish a secure connection to it. To learn more about " \
"this situation and\nhow to fix it, please visit the web page mentioned " \
"above.\n"
static bool is_fatal_error(CURLcode code)
{
switch(code) {
case CURLE_FAILED_INIT:
case CURLE_OUT_OF_MEMORY:
case CURLE_UNKNOWN_OPTION:
case CURLE_FUNCTION_NOT_FOUND:
case CURLE_BAD_FUNCTION_ARGUMENT:
/* critical error */
return TRUE;
default:
break;
}
/* no error or not critical */
return FALSE;
}
/*
* Check if a given string is a PKCS#11 URI
*/
static bool is_pkcs11_uri(const char *string)
{
if(curl_strnequal(string, "pkcs11:", 7)) {
return TRUE;
}
else {
return FALSE;
}
}
#ifdef __VMS
/*
* get_vms_file_size does what it takes to get the real size of the file
*
* For fixed files, find out the size of the EOF block and adjust.
*
* For all others, have to read the entire file in, discarding the contents.
* Most posted text files will be small, and binary files like zlib archives
* and CD/DVD images should be either a STREAM_LF format or a fixed format.
*
*/
static curl_off_t vms_realfilesize(const char *name,
const struct_stat *stat_buf)
{
char buffer[8192];
curl_off_t count;
int ret_stat;
FILE * file;
/* !checksrc! disable FOPENMODE 1 */
file = fopen(name, "r"); /* VMS */
if(file == NULL) {
return 0;
}
count = 0;
ret_stat = 1;
while(ret_stat > 0) {
ret_stat = fread(buffer, 1, sizeof(buffer), file);
if(ret_stat != 0)
count += ret_stat;
}
fclose(file);
return count;
}
/*
*
* VmsSpecialSize checks to see if the stat st_size can be trusted and
* if not to call a routine to get the correct size.
*
*/
static curl_off_t VmsSpecialSize(const char *name,
const struct_stat *stat_buf)
{
switch(stat_buf->st_fab_rfm) {
case FAB$C_VAR:
case FAB$C_VFC:
return vms_realfilesize(name, stat_buf);
break;
default:
return stat_buf->st_size;
}
}
#endif /* __VMS */
#define BUFFER_SIZE (100*1024)
static CURLcode operate_do(struct GlobalConfig *global,
struct OperationConfig *config)
{
char errorbuffer[CURL_ERROR_SIZE];
struct ProgressData progressbar;
struct getout *urlnode;
struct HdrCbData hdrcbdata;
struct OutStruct heads;
metalinkfile *mlfile_last = NULL;
CURL *curl = config->easy;
char *httpgetfields = NULL;
CURLcode result = CURLE_OK;
unsigned long li;
bool capath_from_env;
/* Save the values of noprogress and isatty to restore them later on */
bool orig_noprogress = global->noprogress;
bool orig_isatty = global->isatty;
errorbuffer[0] = '\0';
/* default headers output stream is stdout */
memset(&hdrcbdata, 0, sizeof(struct HdrCbData));
memset(&heads, 0, sizeof(struct OutStruct));
heads.stream = stdout;
heads.config = config;
/*
** Beyond this point no return'ing from this function allowed.
** Jump to label 'quit_curl' in order to abandon this function
** from outside of nested loops further down below.
*/
/* Check we have a url */
if(!config->url_list || !config->url_list->url) {
helpf(global->errors, "no URL specified!\n");
result = CURLE_FAILED_INIT;
goto quit_curl;
}
/* On WIN32 we can't set the path to curl-ca-bundle.crt
* at compile time. So we look here for the file in two ways:
* 1: look at the environment variable CURL_CA_BUNDLE for a path
* 2: if #1 isn't found, use the windows API function SearchPath()
* to find it along the app's path (includes app's dir and CWD)
*
* We support the environment variable thing for non-Windows platforms
* too. Just for the sake of it.
*/
capath_from_env = false;
if(!config->cacert &&
!config->capath &&
!config->insecure_ok) {
struct curl_tlssessioninfo *tls_backend_info = NULL;
/* With the addition of CAINFO support for Schannel, this search could find
* a certificate bundle that was previously ignored. To maintain backward
* compatibility, only perform this search if not using Schannel.
*/
result = curl_easy_getinfo(config->easy,
CURLINFO_TLS_SSL_PTR,
&tls_backend_info);
if(result) {
goto quit_curl;
}
/* Set the CA cert locations specified in the environment. For Windows if
* no environment-specified filename is found then check for CA bundle
* default filename curl-ca-bundle.crt in the user's PATH.
*
* If Schannel is the selected SSL backend then these locations are
* ignored. We allow setting CA location for schannel only when explicitly
* specified by the user via CURLOPT_CAINFO / --cacert.
*/
if(tls_backend_info->backend != CURLSSLBACKEND_SCHANNEL) {
char *env;
env = curlx_getenv("CURL_CA_BUNDLE");
if(env) {
config->cacert = strdup(env);
if(!config->cacert) {
curl_free(env);
helpf(global->errors, "out of memory\n");
result = CURLE_OUT_OF_MEMORY;
goto quit_curl;
}
}
else {
env = curlx_getenv("SSL_CERT_DIR");
if(env) {
config->capath = strdup(env);
if(!config->capath) {
curl_free(env);
helpf(global->errors, "out of memory\n");
result = CURLE_OUT_OF_MEMORY;
goto quit_curl;
}
capath_from_env = true;
}
else {
env = curlx_getenv("SSL_CERT_FILE");
if(env) {
config->cacert = strdup(env);
if(!config->cacert) {
curl_free(env);
helpf(global->errors, "out of memory\n");
result = CURLE_OUT_OF_MEMORY;
goto quit_curl;
}
}
}
}
if(env)
curl_free(env);
#ifdef WIN32
else {
result = FindWin32CACert(config, tls_backend_info->backend,
"curl-ca-bundle.crt");
if(result)
goto quit_curl;
}
#endif
}
}
if(config->postfields) {
if(config->use_httpget) {
/* Use the postfields data for a http get */
httpgetfields = strdup(config->postfields);
Curl_safefree(config->postfields);
if(!httpgetfields) {
helpf(global->errors, "out of memory\n");
result = CURLE_OUT_OF_MEMORY;
goto quit_curl;
}
if(SetHTTPrequest(config,
(config->no_body?HTTPREQ_HEAD:HTTPREQ_GET),
&config->httpreq)) {
result = CURLE_FAILED_INIT;
goto quit_curl;
}
}
else {
if(SetHTTPrequest(config, HTTPREQ_SIMPLEPOST, &config->httpreq)) {
result = CURLE_FAILED_INIT;
goto quit_curl;
}
}
}
/* Single header file for all URLs */
if(config->headerfile) {
/* open file for output: */
if(strcmp(config->headerfile, "-")) {
FILE *newfile = fopen(config->headerfile, "wb");
if(!newfile) {
warnf(config->global, "Failed to open %s\n", config->headerfile);
result = CURLE_WRITE_ERROR;
goto quit_curl;
}
else {
heads.filename = config->headerfile;
heads.s_isreg = TRUE;
heads.fopened = TRUE;
heads.stream = newfile;
}
}
else {
/* always use binary mode for protocol header output */
set_binmode(heads.stream);
}
}
/*
** Nested loops start here.
*/
/* loop through the list of given URLs */
for(urlnode = config->url_list; urlnode; urlnode = urlnode->next) {
unsigned long up; /* upload file counter within a single upload glob */
char *infiles; /* might be a glob pattern */
char *outfiles;
unsigned long infilenum;
URLGlob *inglob;
int metalink = 0; /* nonzero for metalink download. */
metalinkfile *mlfile;
metalink_resource *mlres;
outfiles = NULL;
infilenum = 1;
inglob = NULL;
if(urlnode->flags & GETOUT_METALINK) {
metalink = 1;
if(mlfile_last == NULL) {
mlfile_last = config->metalinkfile_list;
}
mlfile = mlfile_last;
mlfile_last = mlfile_last->next;
mlres = mlfile->resource;
}
else {
mlfile = NULL;
mlres = NULL;
}
/* urlnode->url is the full URL (it might be NULL) */
if(!urlnode->url) {
/* This node has no URL. Free node data without destroying the
node itself nor modifying next pointer and continue to next */
Curl_safefree(urlnode->outfile);
Curl_safefree(urlnode->infile);
urlnode->flags = 0;
continue; /* next URL please */
}
/* save outfile pattern before expansion */
if(urlnode->outfile) {
outfiles = strdup(urlnode->outfile);
if(!outfiles) {
helpf(global->errors, "out of memory\n");
result = CURLE_OUT_OF_MEMORY;
break;
}
}
infiles = urlnode->infile;
if(!config->globoff && infiles) {
/* Unless explicitly shut off */
result = glob_url(&inglob, infiles, &infilenum,
global->showerror?global->errors:NULL);
if(result) {
Curl_safefree(outfiles);
break;
}
}
/* Here's the loop for uploading multiple files within the same
single globbed string. If no upload, we enter the loop once anyway. */
for(up = 0 ; up < infilenum; up++) {
char *uploadfile; /* a single file, never a glob */
int separator;
URLGlob *urls;
unsigned long urlnum;
uploadfile = NULL;
urls = NULL;
urlnum = 0;
if(!up && !infiles)
Curl_nop_stmt;
else {
if(inglob) {
result = glob_next_url(&uploadfile, inglob);
if(result == CURLE_OUT_OF_MEMORY)
helpf(global->errors, "out of memory\n");
}
else if(!up) {
uploadfile = strdup(infiles);
if(!uploadfile) {
helpf(global->errors, "out of memory\n");
result = CURLE_OUT_OF_MEMORY;
}
}
else
uploadfile = NULL;
if(!uploadfile)
break;
}
if(metalink) {
/* For Metalink download, we don't use glob. Instead we use
the number of resources as urlnum. */
urlnum = count_next_metalink_resource(mlfile);
}
else if(!config->globoff) {
/* Unless explicitly shut off, we expand '{...}' and '[...]'
expressions and return total number of URLs in pattern set */
result = glob_url(&urls, urlnode->url, &urlnum,
global->showerror?global->errors:NULL);
if(result) {
Curl_safefree(uploadfile);
break;
}
}
else
urlnum = 1; /* without globbing, this is a single URL */
/* if multiple files extracted to stdout, insert separators! */
separator = ((!outfiles || !strcmp(outfiles, "-")) && urlnum > 1);
/* Here's looping around each globbed URL */
for(li = 0 ; li < urlnum; li++) {
int infd;
bool infdopen;
char *outfile;
struct OutStruct outs;
struct InStruct input;
struct timeval retrystart;
curl_off_t uploadfilesize;
long retry_numretries;
long retry_sleep_default;
long retry_sleep;
char *this_url = NULL;
int metalink_next_res = 0;
outfile = NULL;
infdopen = FALSE;
infd = STDIN_FILENO;
uploadfilesize = -1; /* -1 means unknown */
/* default output stream is stdout */
memset(&outs, 0, sizeof(struct OutStruct));
outs.stream = stdout;
outs.config = config;
if(metalink) {
/* For Metalink download, use name in Metalink file as
filename. */
outfile = strdup(mlfile->filename);
if(!outfile) {
result = CURLE_OUT_OF_MEMORY;
goto show_error;
}
this_url = strdup(mlres->url);
if(!this_url) {
result = CURLE_OUT_OF_MEMORY;
goto show_error;
}
}
else {
if(urls) {
result = glob_next_url(&this_url, urls);
if(result)
goto show_error;
}
else if(!li) {
this_url = strdup(urlnode->url);
if(!this_url) {
result = CURLE_OUT_OF_MEMORY;
goto show_error;
}
}
else
this_url = NULL;
if(!this_url)
break;
if(outfiles) {
outfile = strdup(outfiles);
if(!outfile) {
result = CURLE_OUT_OF_MEMORY;
goto show_error;
}
}
}
if(((urlnode->flags&GETOUT_USEREMOTE) ||
(outfile && strcmp("-", outfile))) &&
(metalink || !config->use_metalink)) {
/*
* We have specified a file name to store the result in, or we have
* decided we want to use the remote file name.
*/
if(!outfile) {
/* extract the file name from the URL */
result = get_url_file_name(&outfile, this_url);
if(result)
goto show_error;
if(!*outfile && !config->content_disposition) {
helpf(global->errors, "Remote file name has no length!\n");
result = CURLE_WRITE_ERROR;
goto quit_urls;
}
}
else if(urls) {
/* fill '#1' ... '#9' terms from URL pattern */
char *storefile = outfile;
result = glob_match_url(&outfile, storefile, urls);
Curl_safefree(storefile);
if(result) {
/* bad globbing */
warnf(config->global, "bad output glob!\n");
goto quit_urls;
}
}
/* Create the directory hierarchy, if not pre-existent to a multiple
file output call */
if(config->create_dirs || metalink) {
result = create_dir_hierarchy(outfile, global->errors);
/* create_dir_hierarchy shows error upon CURLE_WRITE_ERROR */
if(result == CURLE_WRITE_ERROR)
goto quit_urls;
if(result) {
goto show_error;
}
}
if((urlnode->flags & GETOUT_USEREMOTE)
&& config->content_disposition) {
/* Our header callback MIGHT set the filename */
DEBUGASSERT(!outs.filename);
}
if(config->resume_from_current) {
/* We're told to continue from where we are now. Get the size
of the file as it is now and open it for append instead */
struct_stat fileinfo;
/* VMS -- Danger, the filesize is only valid for stream files */
if(0 == stat(outfile, &fileinfo))
/* set offset to current file size: */
config->resume_from = fileinfo.st_size;
else
/* let offset be 0 */
config->resume_from = 0;
}
if(config->resume_from) {
#ifdef __VMS
/* open file for output, forcing VMS output format into stream
mode which is needed for stat() call above to always work. */
FILE *file = fopen(outfile, config->resume_from?"ab":"wb",
"ctx=stm", "rfm=stmlf", "rat=cr", "mrs=0");
#else
/* open file for output: */
FILE *file = fopen(outfile, config->resume_from?"ab":"wb");
#endif
if(!file) {
helpf(global->errors, "Can't open '%s'!\n", outfile);
result = CURLE_WRITE_ERROR;
goto quit_urls;
}
outs.fopened = TRUE;
outs.stream = file;
outs.init = config->resume_from;
}
else {
outs.stream = NULL; /* open when needed */
}
outs.filename = outfile;
outs.s_isreg = TRUE;
}
if(uploadfile && !stdin_upload(uploadfile)) {
/*
* We have specified a file to upload and it isn't "-".
*/
struct_stat fileinfo;
this_url = add_file_name_to_url(curl, this_url, uploadfile);
if(!this_url) {
result = CURLE_OUT_OF_MEMORY;
goto show_error;
}
/* VMS Note:
*
* Reading binary from files can be a problem... Only FIXED, VAR
* etc WITHOUT implied CC will work Others need a \n appended to a
* line
*
* - Stat gives a size but this is UNRELIABLE in VMS As a f.e. a
* fixed file with implied CC needs to have a byte added for every
* record processed, this can by derived from Filesize & recordsize
* for VARiable record files the records need to be counted! for
* every record add 1 for linefeed and subtract 2 for the record
* header for VARIABLE header files only the bare record data needs
* to be considered with one appended if implied CC
*/
#ifdef __VMS
/* Calculate the real upload size for VMS */
infd = -1;
if(stat(uploadfile, &fileinfo) == 0) {
fileinfo.st_size = VmsSpecialSize(uploadfile, &fileinfo);
switch(fileinfo.st_fab_rfm) {
case FAB$C_VAR:
case FAB$C_VFC:
case FAB$C_STMCR:
infd = open(uploadfile, O_RDONLY | O_BINARY);
break;
default:
infd = open(uploadfile, O_RDONLY | O_BINARY,
"rfm=stmlf", "ctx=stm");
}
}
if(infd == -1)
#else
infd = open(uploadfile, O_RDONLY | O_BINARY);
if((infd == -1) || fstat(infd, &fileinfo))
#endif
{
helpf(global->errors, "Can't open '%s'!\n", uploadfile);
if(infd != -1) {
close(infd);
infd = STDIN_FILENO;
}
result = CURLE_READ_ERROR;
goto quit_urls;
}
infdopen = TRUE;
/* we ignore file size for char/block devices, sockets, etc. */
if(S_ISREG(fileinfo.st_mode))
uploadfilesize = fileinfo.st_size;
}
else if(uploadfile && stdin_upload(uploadfile)) {
/* count to see if there are more than one auth bit set
in the authtype field */
int authbits = 0;
int bitcheck = 0;
while(bitcheck < 32) {
if(config->authtype & (1UL << bitcheck++)) {
authbits++;
if(authbits > 1) {
/* more than one, we're done! */
break;
}
}
}
/*
* If the user has also selected --anyauth or --proxy-anyauth
* we should warn him/her.
*/
if(config->proxyanyauth || (authbits>1)) {
warnf(config->global,
"Using --anyauth or --proxy-anyauth with upload from stdin"
" involves a big risk of it not working. Use a temporary"
" file or a fixed auth type instead!\n");
}
DEBUGASSERT(infdopen == FALSE);
DEBUGASSERT(infd == STDIN_FILENO);
set_binmode(stdin);
if(!strcmp(uploadfile, ".")) {
if(curlx_nonblock((curl_socket_t)infd, TRUE) < 0)
warnf(config->global,
"fcntl failed on fd=%d: %s\n", infd, strerror(errno));
}
}
if(uploadfile && config->resume_from_current)
config->resume_from = -1; /* -1 will then force get-it-yourself */
if(output_expected(this_url, uploadfile) && outs.stream &&
isatty(fileno(outs.stream)))
/* we send the output to a tty, therefore we switch off the progress
meter */
global->noprogress = global->isatty = TRUE;
else {
/* progress meter is per download, so restore config
values */
global->noprogress = orig_noprogress;
global->isatty = orig_isatty;
}
if(urlnum > 1 && !global->mute) {
fprintf(global->errors, "\n[%lu/%lu]: %s --> %s\n",
li + 1, urlnum, this_url, outfile ? outfile : "<stdout>");
if(separator)
printf("%s%s\n", CURLseparator, this_url);
}
if(httpgetfields) {
char *urlbuffer;
/* Find out whether the url contains a file name */
const char *pc = strstr(this_url, "://");
char sep = '?';
if(pc)
pc += 3;
else
pc = this_url;
pc = strrchr(pc, '/'); /* check for a slash */
if(pc) {
/* there is a slash present in the URL */
if(strchr(pc, '?'))
/* Ouch, there's already a question mark in the URL string, we
then append the data with an ampersand separator instead! */
sep = '&';
}
/*
* Then append ? followed by the get fields to the url.
*/
if(pc)
urlbuffer = aprintf("%s%c%s", this_url, sep, httpgetfields);
else
/* Append / before the ? to create a well-formed url
if the url contains a hostname only
*/
urlbuffer = aprintf("%s/?%s", this_url, httpgetfields);
if(!urlbuffer) {
result = CURLE_OUT_OF_MEMORY;
goto show_error;
}
Curl_safefree(this_url); /* free previous URL */
this_url = urlbuffer; /* use our new URL instead! */
}
if(!global->errors)
global->errors = stderr;
if((!outfile || !strcmp(outfile, "-")) && !config->use_ascii) {
/* We get the output to stdout and we have not got the ASCII/text
flag, then set stdout to be binary */
set_binmode(stdout);
}
/* explicitly passed to stdout means okaying binary gunk */
config->terminal_binary_ok = (outfile && !strcmp(outfile, "-"));
if(!config->tcp_nodelay)
my_setopt(curl, CURLOPT_TCP_NODELAY, 0L);
if(config->tcp_fastopen)
my_setopt(curl, CURLOPT_TCP_FASTOPEN, 1L);
/* where to store */
my_setopt(curl, CURLOPT_WRITEDATA, &outs);
#ifndef CURL_DISABLE_RTSP
my_setopt(curl, CURLOPT_INTERLEAVEDATA, &outs);
#endif
if(metalink || !config->use_metalink)
/* what call to write */
my_setopt(curl, CURLOPT_WRITEFUNCTION, tool_write_cb);
#ifdef USE_METALINK
else
/* Set Metalink specific write callback function to parse
XML data progressively. */
my_setopt(curl, CURLOPT_WRITEFUNCTION, metalink_write_cb);
#endif /* USE_METALINK */
/* for uploads */
input.fd = infd;
input.config = config;
/* Note that if CURLOPT_READFUNCTION is fread (the default), then
* lib/telnet.c will Curl_poll() on the input file descriptor
* rather then calling the READFUNCTION at regular intervals.
* The circumstances in which it is preferable to enable this
* behaviour, by omitting to set the READFUNCTION & READDATA options,
* have not been determined.
*/
my_setopt(curl, CURLOPT_READDATA, &input);
/* what call to read */
my_setopt(curl, CURLOPT_READFUNCTION, tool_read_cb);
/* in 7.18.0, the CURLOPT_SEEKFUNCTION/DATA pair is taking over what
CURLOPT_IOCTLFUNCTION/DATA pair previously provided for seeking */
my_setopt(curl, CURLOPT_SEEKDATA, &input);
my_setopt(curl, CURLOPT_SEEKFUNCTION, tool_seek_cb);
if(config->recvpersecond &&
(config->recvpersecond < BUFFER_SIZE))
/* use a smaller sized buffer for better sleeps */
my_setopt(curl, CURLOPT_BUFFERSIZE, (long)config->recvpersecond);
else
my_setopt(curl, CURLOPT_BUFFERSIZE, (long)BUFFER_SIZE);
/* size of uploaded file: */
if(uploadfilesize != -1)
my_setopt(curl, CURLOPT_INFILESIZE_LARGE, uploadfilesize);
my_setopt_str(curl, CURLOPT_URL, this_url); /* what to fetch */
my_setopt(curl, CURLOPT_NOPROGRESS, global->noprogress?1L:0L);
if(config->no_body)
my_setopt(curl, CURLOPT_NOBODY, 1L);
if(config->oauth_bearer)
my_setopt_str(curl, CURLOPT_XOAUTH2_BEARER, config->oauth_bearer);
#if !defined(CURL_DISABLE_PROXY)
{
my_setopt_str(curl, CURLOPT_PROXY, config->proxy);
/* new in libcurl 7.5 */
if(config->proxy)
my_setopt_enum(curl, CURLOPT_PROXYTYPE, config->proxyver);
my_setopt_str(curl, CURLOPT_PROXYUSERPWD, config->proxyuserpwd);
/* new in libcurl 7.3 */
my_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, config->proxytunnel?1L:0L);
/* new in libcurl 7.52.0 */
if(config->preproxy)
my_setopt_str(curl, CURLOPT_PRE_PROXY, config->preproxy);
/* new in libcurl 7.10.6 */
if(config->proxyanyauth)
my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
(long)CURLAUTH_ANY);
else if(config->proxynegotiate)
my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
(long)CURLAUTH_GSSNEGOTIATE);
else if(config->proxyntlm)
my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
(long)CURLAUTH_NTLM);
else if(config->proxydigest)
my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
(long)CURLAUTH_DIGEST);
else if(config->proxybasic)
my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
(long)CURLAUTH_BASIC);
/* new in libcurl 7.19.4 */
my_setopt_str(curl, CURLOPT_NOPROXY, config->noproxy);
my_setopt(curl, CURLOPT_SUPPRESS_CONNECT_HEADERS,
config->suppress_connect_headers?1L:0L);
}
#endif /* !CURL_DISABLE_PROXY */
my_setopt(curl, CURLOPT_FAILONERROR, config->failonerror?1L:0L);
my_setopt(curl, CURLOPT_REQUEST_TARGET, config->request_target);
my_setopt(curl, CURLOPT_UPLOAD, uploadfile?1L:0L);
my_setopt(curl, CURLOPT_DIRLISTONLY, config->dirlistonly?1L:0L);
my_setopt(curl, CURLOPT_APPEND, config->ftp_append?1L:0L);
if(config->netrc_opt)
my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_OPTIONAL);
else if(config->netrc || config->netrc_file)
my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_REQUIRED);
else
my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_IGNORED);
if(config->netrc_file)
my_setopt_str(curl, CURLOPT_NETRC_FILE, config->netrc_file);
my_setopt(curl, CURLOPT_TRANSFERTEXT, config->use_ascii?1L:0L);
if(config->login_options)
my_setopt_str(curl, CURLOPT_LOGIN_OPTIONS, config->login_options);
my_setopt_str(curl, CURLOPT_USERPWD, config->userpwd);
my_setopt_str(curl, CURLOPT_RANGE, config->range);
my_setopt(curl, CURLOPT_ERRORBUFFER, errorbuffer);
my_setopt(curl, CURLOPT_TIMEOUT_MS, (long)(config->timeout * 1000));
switch(config->httpreq) {
case HTTPREQ_SIMPLEPOST:
my_setopt_str(curl, CURLOPT_POSTFIELDS,
config->postfields);
my_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE,
config->postfieldsize);
break;
case HTTPREQ_MIMEPOST:
result = tool2curlmime(curl, config->mimeroot, &config->mimepost);
if(result)
goto show_error;
my_setopt_mimepost(curl, CURLOPT_MIMEPOST, config->mimepost);
break;
default:
break;
}
/* new in libcurl 7.10.6 (default is Basic) */
if(config->authtype)
my_setopt_bitmask(curl, CURLOPT_HTTPAUTH, (long)config->authtype);
my_setopt_slist(curl, CURLOPT_HTTPHEADER, config->headers);
if(built_in_protos & (CURLPROTO_HTTP | CURLPROTO_RTSP)) {
my_setopt_str(curl, CURLOPT_REFERER, config->referer);
my_setopt_str(curl, CURLOPT_USERAGENT, config->useragent);
}
if(built_in_protos & CURLPROTO_HTTP) {
long postRedir = 0;
my_setopt(curl, CURLOPT_FOLLOWLOCATION,
config->followlocation?1L:0L);
my_setopt(curl, CURLOPT_UNRESTRICTED_AUTH,
config->unrestricted_auth?1L:0L);
my_setopt(curl, CURLOPT_AUTOREFERER, config->autoreferer?1L:0L);
/* new in libcurl 7.36.0 */
if(config->proxyheaders) {
my_setopt_slist(curl, CURLOPT_PROXYHEADER, config->proxyheaders);
my_setopt(curl, CURLOPT_HEADEROPT, CURLHEADER_SEPARATE);
}
/* new in libcurl 7.5 */
my_setopt(curl, CURLOPT_MAXREDIRS, config->maxredirs);
if(config->httpversion)
my_setopt_enum(curl, CURLOPT_HTTP_VERSION, config->httpversion);
else if(curlinfo->features & CURL_VERSION_HTTP2) {
my_setopt_enum(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
}
/* curl 7.19.1 (the 301 version existed in 7.18.2),
303 was added in 7.26.0 */
if(config->post301)
postRedir |= CURL_REDIR_POST_301;
if(config->post302)
postRedir |= CURL_REDIR_POST_302;
if(config->post303)
postRedir |= CURL_REDIR_POST_303;
my_setopt(curl, CURLOPT_POSTREDIR, postRedir);
/* new in libcurl 7.21.6 */
if(config->encoding)
my_setopt_str(curl, CURLOPT_ACCEPT_ENCODING, "");
/* new in libcurl 7.21.6 */
if(config->tr_encoding)
my_setopt(curl, CURLOPT_TRANSFER_ENCODING, 1L);
/* new in libcurl 7.64.0 */
my_setopt(curl, CURLOPT_HTTP09_ALLOWED,
config->http09_allowed ? 1L : 0L);
} /* (built_in_protos & CURLPROTO_HTTP) */
#ifndef CURL_DISABLE_FTP
my_setopt_str(curl, CURLOPT_FTPPORT, config->ftpport);
#endif
my_setopt(curl, CURLOPT_LOW_SPEED_LIMIT,
config->low_speed_limit);
my_setopt(curl, CURLOPT_LOW_SPEED_TIME, config->low_speed_time);
my_setopt(curl, CURLOPT_MAX_SEND_SPEED_LARGE,
config->sendpersecond);
my_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE,
config->recvpersecond);
if(config->use_resume)
my_setopt(curl, CURLOPT_RESUME_FROM_LARGE, config->resume_from);
else
my_setopt(curl, CURLOPT_RESUME_FROM_LARGE, CURL_OFF_T_C(0));
my_setopt_str(curl, CURLOPT_KEYPASSWD, config->key_passwd);
#ifndef CURL_DISABLE_PROXY
my_setopt_str(curl, CURLOPT_PROXY_KEYPASSWD, config->proxy_key_passwd);
#endif
if(built_in_protos & (CURLPROTO_SCP|CURLPROTO_SFTP)) {
/* SSH and SSL private key uses same command-line option */
/* new in libcurl 7.16.1 */
my_setopt_str(curl, CURLOPT_SSH_PRIVATE_KEYFILE, config->key);
/* new in libcurl 7.16.1 */
my_setopt_str(curl, CURLOPT_SSH_PUBLIC_KEYFILE, config->pubkey);
/* new in libcurl 7.17.1: SSH host key md5 checking allows us
to fail if we are not talking to who we think we should */
my_setopt_str(curl, CURLOPT_SSH_HOST_PUBLIC_KEY_MD5,
config->hostpubmd5);
/* new in libcurl 7.56.0 */
if(config->ssh_compression)
my_setopt(curl, CURLOPT_SSH_COMPRESSION, 1L);
}
if(config->cacert)
my_setopt_str(curl, CURLOPT_CAINFO, config->cacert);
if(config->proxy_cacert)
my_setopt_str(curl, CURLOPT_PROXY_CAINFO, config->proxy_cacert);
if(config->capath) {
result = res_setopt_str(curl, CURLOPT_CAPATH, config->capath);
if(result == CURLE_NOT_BUILT_IN) {
warnf(config->global, "ignoring %s, not supported by libcurl\n",
capath_from_env?
"SSL_CERT_DIR environment variable":"--capath");
}
else if(result)
goto show_error;
}
/* For the time being if --proxy-capath is not set then we use the
--capath value for it, if any. See #1257 */
if(config->proxy_capath || config->capath) {
result = res_setopt_str(curl, CURLOPT_PROXY_CAPATH,
(config->proxy_capath ?
config->proxy_capath :
config->capath));
if(result == CURLE_NOT_BUILT_IN) {
if(config->proxy_capath) {
warnf(config->global,
"ignoring --proxy-capath, not supported by libcurl\n");
}
}
else if(result)
goto show_error;
}
if(config->crlfile)
my_setopt_str(curl, CURLOPT_CRLFILE, config->crlfile);
if(config->proxy_crlfile)
my_setopt_str(curl, CURLOPT_PROXY_CRLFILE, config->proxy_crlfile);
else if(config->crlfile) /* CURLOPT_PROXY_CRLFILE default is crlfile */
my_setopt_str(curl, CURLOPT_PROXY_CRLFILE, config->crlfile);
if(config->pinnedpubkey)
my_setopt_str(curl, CURLOPT_PINNEDPUBLICKEY, config->pinnedpubkey);
if(curlinfo->features & CURL_VERSION_SSL) {
/* Check if config->cert is a PKCS#11 URI and set the
* config->cert_type if necessary */
if(config->cert) {
if(!config->cert_type) {
if(is_pkcs11_uri(config->cert)) {
config->cert_type = strdup("ENG");
}
}
}
/* Check if config->key is a PKCS#11 URI and set the
* config->key_type if necessary */
if(config->key) {
if(!config->key_type) {
if(is_pkcs11_uri(config->key)) {
config->key_type = strdup("ENG");
}
}
}
/* Check if config->proxy_cert is a PKCS#11 URI and set the
* config->proxy_type if necessary */
if(config->proxy_cert) {
if(!config->proxy_cert_type) {
if(is_pkcs11_uri(config->proxy_cert)) {
config->proxy_cert_type = strdup("ENG");
}
}
}
/* Check if config->proxy_key is a PKCS#11 URI and set the
* config->proxy_key_type if necessary */
if(config->proxy_key) {
if(!config->proxy_key_type) {
if(is_pkcs11_uri(config->proxy_key)) {
config->proxy_key_type = strdup("ENG");
}
}
}
my_setopt_str(curl, CURLOPT_SSLCERT, config->cert);
my_setopt_str(curl, CURLOPT_PROXY_SSLCERT, config->proxy_cert);
my_setopt_str(curl, CURLOPT_SSLCERTTYPE, config->cert_type);
my_setopt_str(curl, CURLOPT_PROXY_SSLCERTTYPE,
config->proxy_cert_type);
my_setopt_str(curl, CURLOPT_SSLKEY, config->key);
my_setopt_str(curl, CURLOPT_PROXY_SSLKEY, config->proxy_key);
my_setopt_str(curl, CURLOPT_SSLKEYTYPE, config->key_type);
my_setopt_str(curl, CURLOPT_PROXY_SSLKEYTYPE,
config->proxy_key_type);
if(config->insecure_ok) {
my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
}
else {
my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
/* libcurl default is strict verifyhost -> 2L */
/* my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); */
}
if(config->proxy_insecure_ok) {
my_setopt(curl, CURLOPT_PROXY_SSL_VERIFYPEER, 0L);
my_setopt(curl, CURLOPT_PROXY_SSL_VERIFYHOST, 0L);
}
else {
my_setopt(curl, CURLOPT_PROXY_SSL_VERIFYPEER, 1L);
}
if(config->verifystatus)
my_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 1L);
if(config->falsestart)
my_setopt(curl, CURLOPT_SSL_FALSESTART, 1L);
my_setopt_enum(curl, CURLOPT_SSLVERSION,
config->ssl_version | config->ssl_version_max);
my_setopt_enum(curl, CURLOPT_PROXY_SSLVERSION,
config->proxy_ssl_version);
}
if(config->path_as_is)
my_setopt(curl, CURLOPT_PATH_AS_IS, 1L);
if(built_in_protos & (CURLPROTO_SCP|CURLPROTO_SFTP)) {
if(!config->insecure_ok) {
char *home;
char *file;
result = CURLE_OUT_OF_MEMORY;
home = homedir();
if(home) {
file = aprintf("%s/%sssh/known_hosts", home, DOT_CHAR);
if(file) {
/* new in curl 7.19.6 */
result = res_setopt_str(curl, CURLOPT_SSH_KNOWNHOSTS, file);
curl_free(file);
if(result == CURLE_UNKNOWN_OPTION)
/* libssh2 version older than 1.1.1 */
result = CURLE_OK;
}
Curl_safefree(home);
}
if(result)
goto show_error;
}
}
if(config->no_body || config->remote_time) {
/* no body or use remote time */
my_setopt(curl, CURLOPT_FILETIME, 1L);
}
my_setopt(curl, CURLOPT_CRLF, config->crlf?1L:0L);
my_setopt_slist(curl, CURLOPT_QUOTE, config->quote);
my_setopt_slist(curl, CURLOPT_POSTQUOTE, config->postquote);
my_setopt_slist(curl, CURLOPT_PREQUOTE, config->prequote);
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
if(config->cookie)
my_setopt_str(curl, CURLOPT_COOKIE, config->cookie);
if(config->cookiefile)
my_setopt_str(curl, CURLOPT_COOKIEFILE, config->cookiefile);
/* new in libcurl 7.9 */
if(config->cookiejar)
my_setopt_str(curl, CURLOPT_COOKIEJAR, config->cookiejar);
/* new in libcurl 7.9.7 */
my_setopt(curl, CURLOPT_COOKIESESSION, config->cookiesession?1L:0L);
#else
if(config->cookie || config->cookiefile || config->cookiejar) {
warnf(config->global, "cookie option(s) used even though cookie "
"support is disabled!\n");
return CURLE_NOT_BUILT_IN;
}
#endif
my_setopt_enum(curl, CURLOPT_TIMECONDITION, (long)config->timecond);
my_setopt(curl, CURLOPT_TIMEVALUE_LARGE, config->condtime);
my_setopt_str(curl, CURLOPT_CUSTOMREQUEST, config->customrequest);
customrequest_helper(config, config->httpreq, config->customrequest);
my_setopt(curl, CURLOPT_STDERR, global->errors);
/* three new ones in libcurl 7.3: */
my_setopt_str(curl, CURLOPT_INTERFACE, config->iface);
#ifndef CURL_DISABLE_FTP
my_setopt_str(curl, CURLOPT_KRBLEVEL, config->krblevel);
#endif
progressbarinit(&progressbar, config);
if((global->progressmode == CURL_PROGRESS_BAR) &&
!global->noprogress && !global->mute) {
/* we want the alternative style, then we have to implement it
ourselves! */
my_setopt(curl, CURLOPT_XFERINFOFUNCTION, tool_progress_cb);
my_setopt(curl, CURLOPT_XFERINFODATA, &progressbar);
}
/* new in libcurl 7.24.0: */
if(config->dns_servers)
my_setopt_str(curl, CURLOPT_DNS_SERVERS, config->dns_servers);
/* new in libcurl 7.33.0: */
if(config->dns_interface)
my_setopt_str(curl, CURLOPT_DNS_INTERFACE, config->dns_interface);
if(config->dns_ipv4_addr)
my_setopt_str(curl, CURLOPT_DNS_LOCAL_IP4, config->dns_ipv4_addr);
if(config->dns_ipv6_addr)
my_setopt_str(curl, CURLOPT_DNS_LOCAL_IP6, config->dns_ipv6_addr);
#ifndef CURL_DISABLE_TELNET
/* new in libcurl 7.6.2: */
my_setopt_slist(curl, CURLOPT_TELNETOPTIONS, config->telnet_options);
#endif
/* new in libcurl 7.7: */
my_setopt_str(curl, CURLOPT_RANDOM_FILE, config->random_file);
my_setopt_str(curl, CURLOPT_EGDSOCKET, config->egd_file);
my_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
(long)(config->connecttimeout * 1000));
if(config->doh_url)
my_setopt_str(curl, CURLOPT_DOH_URL, config->doh_url);
if(config->cipher_list)
my_setopt_str(curl, CURLOPT_SSL_CIPHER_LIST, config->cipher_list);
if(config->proxy_cipher_list)
my_setopt_str(curl, CURLOPT_PROXY_SSL_CIPHER_LIST,
config->proxy_cipher_list);
if(config->cipher13_list)
my_setopt_str(curl, CURLOPT_TLS13_CIPHERS, config->cipher13_list);
if(config->proxy_cipher13_list)
my_setopt_str(curl, CURLOPT_PROXY_TLS13_CIPHERS,
config->proxy_cipher13_list);
/* new in libcurl 7.9.2: */
if(config->disable_epsv)
/* disable it */
my_setopt(curl, CURLOPT_FTP_USE_EPSV, 0L);
/* new in libcurl 7.10.5 */
if(config->disable_eprt)
/* disable it */
my_setopt(curl, CURLOPT_FTP_USE_EPRT, 0L);
if(global->tracetype != TRACE_NONE) {
my_setopt(curl, CURLOPT_DEBUGFUNCTION, tool_debug_cb);
my_setopt(curl, CURLOPT_DEBUGDATA, config);
my_setopt(curl, CURLOPT_VERBOSE, 1L);
}
/* new in curl 7.9.3 */
if(config->engine) {
result = res_setopt_str(curl, CURLOPT_SSLENGINE, config->engine);
if(result)
goto show_error;
}
/* new in curl 7.10.7, extended in 7.19.4. Modified to use
CREATE_DIR_RETRY in 7.49.0 */
my_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS,
(long)(config->ftp_create_dirs?
CURLFTP_CREATE_DIR_RETRY:
CURLFTP_CREATE_DIR_NONE));
/* new in curl 7.10.8 */
if(config->max_filesize)
my_setopt(curl, CURLOPT_MAXFILESIZE_LARGE,
config->max_filesize);
if(4 == config->ip_version)
my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
else if(6 == config->ip_version)
my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
else
my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER);
/* new in curl 7.15.5 */
if(config->ftp_ssl_reqd)
my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
/* new in curl 7.11.0 */
else if(config->ftp_ssl)
my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_TRY);
/* new in curl 7.16.0 */
else if(config->ftp_ssl_control)
my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_CONTROL);
/* new in curl 7.16.1 */
if(config->ftp_ssl_ccc)
my_setopt_enum(curl, CURLOPT_FTP_SSL_CCC,
(long)config->ftp_ssl_ccc_mode);
/* new in curl 7.19.4 */
if(config->socks5_gssapi_nec)
my_setopt_str(curl, CURLOPT_SOCKS5_GSSAPI_NEC,
config->socks5_gssapi_nec);
/* new in curl 7.55.0 */
if(config->socks5_auth)
my_setopt_bitmask(curl, CURLOPT_SOCKS5_AUTH,
(long)config->socks5_auth);
/* new in curl 7.43.0 */
if(config->proxy_service_name)
my_setopt_str(curl, CURLOPT_PROXY_SERVICE_NAME,
config->proxy_service_name);
/* new in curl 7.43.0 */
if(config->service_name)
my_setopt_str(curl, CURLOPT_SERVICE_NAME,
config->service_name);
#ifndef CURL_DISABLE_FTP
/* curl 7.13.0 */
my_setopt_str(curl, CURLOPT_FTP_ACCOUNT, config->ftp_account);
#endif
my_setopt(curl, CURLOPT_IGNORE_CONTENT_LENGTH, config->ignorecl?1L:0L);
#ifndef CURL_DISABLE_FTP
/* curl 7.14.2 */
my_setopt(curl, CURLOPT_FTP_SKIP_PASV_IP, config->ftp_skip_ip?1L:0L);
/* curl 7.15.1 */
my_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long)config->ftp_filemethod);
#endif
/* curl 7.15.2 */
if(config->localport) {
my_setopt(curl, CURLOPT_LOCALPORT, config->localport);
my_setopt_str(curl, CURLOPT_LOCALPORTRANGE, config->localportrange);
}
#ifndef CURL_DISABLE_FTP
/* curl 7.15.5 */
my_setopt_str(curl, CURLOPT_FTP_ALTERNATIVE_TO_USER,
config->ftp_alternative_to_user);
#endif
/* curl 7.16.0 */
if(config->disable_sessionid)
/* disable it */
my_setopt(curl, CURLOPT_SSL_SESSIONID_CACHE, 0L);
/* curl 7.16.2 */
if(config->raw) {
my_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 0L);
my_setopt(curl, CURLOPT_HTTP_TRANSFER_DECODING, 0L);
}
/* curl 7.17.1 */
if(!config->nokeepalive) {
my_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
if(config->alivetime != 0) {
my_setopt(curl, CURLOPT_TCP_KEEPIDLE, config->alivetime);
my_setopt(curl, CURLOPT_TCP_KEEPINTVL, config->alivetime);
}
}
else
my_setopt(curl, CURLOPT_TCP_KEEPALIVE, 0L);
/* curl 7.20.0 */
if(config->tftp_blksize)
my_setopt(curl, CURLOPT_TFTP_BLKSIZE, config->tftp_blksize);
if(config->mail_from)
my_setopt_str(curl, CURLOPT_MAIL_FROM, config->mail_from);
if(config->mail_rcpt)
my_setopt_slist(curl, CURLOPT_MAIL_RCPT, config->mail_rcpt);
/* curl 7.20.x */
if(config->ftp_pret)
my_setopt(curl, CURLOPT_FTP_USE_PRET, 1L);
if(config->proto_present)
my_setopt_flags(curl, CURLOPT_PROTOCOLS, config->proto);
if(config->proto_redir_present)
my_setopt_flags(curl, CURLOPT_REDIR_PROTOCOLS, config->proto_redir);
if(config->content_disposition
&& (urlnode->flags & GETOUT_USEREMOTE))
hdrcbdata.honor_cd_filename = TRUE;
else
hdrcbdata.honor_cd_filename = FALSE;
hdrcbdata.outs = &outs;
hdrcbdata.heads = &heads;
hdrcbdata.global = global;
hdrcbdata.config = config;
my_setopt(curl, CURLOPT_HEADERFUNCTION, tool_header_cb);
my_setopt(curl, CURLOPT_HEADERDATA, &hdrcbdata);
if(config->resolve)
/* new in 7.21.3 */
my_setopt_slist(curl, CURLOPT_RESOLVE, config->resolve);
if(config->connect_to)
/* new in 7.49.0 */
my_setopt_slist(curl, CURLOPT_CONNECT_TO, config->connect_to);
/* new in 7.21.4 */
if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) {
if(config->tls_username)
my_setopt_str(curl, CURLOPT_TLSAUTH_USERNAME,
config->tls_username);
if(config->tls_password)
my_setopt_str(curl, CURLOPT_TLSAUTH_PASSWORD,
config->tls_password);
if(config->tls_authtype)
my_setopt_str(curl, CURLOPT_TLSAUTH_TYPE,
config->tls_authtype);
if(config->proxy_tls_username)
my_setopt_str(curl, CURLOPT_PROXY_TLSAUTH_USERNAME,
config->proxy_tls_username);
if(config->proxy_tls_password)
my_setopt_str(curl, CURLOPT_PROXY_TLSAUTH_PASSWORD,
config->proxy_tls_password);
if(config->proxy_tls_authtype)
my_setopt_str(curl, CURLOPT_PROXY_TLSAUTH_TYPE,
config->proxy_tls_authtype);
}
/* new in 7.22.0 */
if(config->gssapi_delegation)
my_setopt_str(curl, CURLOPT_GSSAPI_DELEGATION,
config->gssapi_delegation);
/* new in 7.25.0 and 7.44.0 */
{
long mask = (config->ssl_allow_beast ? CURLSSLOPT_ALLOW_BEAST : 0) |
(config->ssl_no_revoke ? CURLSSLOPT_NO_REVOKE : 0);
if(mask)
my_setopt_bitmask(curl, CURLOPT_SSL_OPTIONS, mask);
}
if(config->proxy_ssl_allow_beast)
my_setopt(curl, CURLOPT_PROXY_SSL_OPTIONS,
(long)CURLSSLOPT_ALLOW_BEAST);
if(config->mail_auth)
my_setopt_str(curl, CURLOPT_MAIL_AUTH, config->mail_auth);
/* new in 7.31.0 */
if(config->sasl_ir)
my_setopt(curl, CURLOPT_SASL_IR, 1L);
if(config->nonpn) {
my_setopt(curl, CURLOPT_SSL_ENABLE_NPN, 0L);
}
if(config->noalpn) {
my_setopt(curl, CURLOPT_SSL_ENABLE_ALPN, 0L);
}
/* new in 7.40.0, abstract support added in 7.53.0 */
if(config->unix_socket_path) {
if(config->abstract_unix_socket) {
my_setopt_str(curl, CURLOPT_ABSTRACT_UNIX_SOCKET,
config->unix_socket_path);
}
else {
my_setopt_str(curl, CURLOPT_UNIX_SOCKET_PATH,
config->unix_socket_path);
}
}
/* new in 7.45.0 */
if(config->proto_default)
my_setopt_str(curl, CURLOPT_DEFAULT_PROTOCOL, config->proto_default);
/* new in 7.47.0 */
if(config->expect100timeout > 0)
my_setopt_str(curl, CURLOPT_EXPECT_100_TIMEOUT_MS,
(long)(config->expect100timeout*1000));
/* new in 7.48.0 */
if(config->tftp_no_options)
my_setopt(curl, CURLOPT_TFTP_NO_OPTIONS, 1L);
/* new in 7.59.0 */
if(config->happy_eyeballs_timeout_ms != CURL_HET_DEFAULT)
my_setopt(curl, CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS,
config->happy_eyeballs_timeout_ms);
/* new in 7.60.0 */
if(config->haproxy_protocol)
my_setopt(curl, CURLOPT_HAPROXYPROTOCOL, 1L);
if(config->disallow_username_in_url)
my_setopt(curl, CURLOPT_DISALLOW_USERNAME_IN_URL, 1L);
#ifdef USE_ALTSVC
/* only if explicitly enabled in configure */
if(config->altsvc)
my_setopt_str(curl, CURLOPT_ALTSVC, config->altsvc);
#endif
/* initialize retry vars for loop below */
retry_sleep_default = (config->retry_delay) ?
config->retry_delay*1000L : RETRY_SLEEP_DEFAULT; /* ms */
retry_numretries = config->req_retry;
retry_sleep = retry_sleep_default; /* ms */
retrystart = tvnow();
#ifndef CURL_DISABLE_LIBCURL_OPTION
if(global->libcurl) {
result = easysrc_perform();
if(result)
goto show_error;
}
#endif
for(;;) {
#ifdef USE_METALINK
if(!metalink && config->use_metalink) {
/* If outs.metalink_parser is non-NULL, delete it first. */
if(outs.metalink_parser)
metalink_parser_context_delete(outs.metalink_parser);
outs.metalink_parser = metalink_parser_context_new();
if(outs.metalink_parser == NULL) {
result = CURLE_OUT_OF_MEMORY;
goto show_error;
}
fprintf(config->global->errors,
"Metalink: parsing (%s) metalink/XML...\n", this_url);
}
else if(metalink)
fprintf(config->global->errors,
"Metalink: fetching (%s) from (%s)...\n",
mlfile->filename, this_url);
#endif /* USE_METALINK */
#ifdef CURLDEBUG
if(config->test_event_based)
result = curl_easy_perform_ev(curl);
else
#endif
result = curl_easy_perform(curl);
if(!result && !outs.stream && !outs.bytes) {
/* we have received no data despite the transfer was successful
==> force cration of an empty output file (if an output file
was specified) */
long cond_unmet = 0L;
/* do not create (or even overwrite) the file in case we get no
data because of unmet condition */
curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &cond_unmet);
if(!cond_unmet && !tool_create_output_file(&outs))
result = CURLE_WRITE_ERROR;
}
if(outs.is_cd_filename && outs.stream && !global->mute &&
outs.filename)
printf("curl: Saved to filename '%s'\n", outs.filename);
/* if retry-max-time is non-zero, make sure we haven't exceeded the
time */
if(retry_numretries &&
(!config->retry_maxtime ||
(tvdiff(tvnow(), retrystart) <
config->retry_maxtime*1000L)) ) {
enum {
RETRY_NO,
RETRY_TIMEOUT,
RETRY_CONNREFUSED,
RETRY_HTTP,
RETRY_FTP,
RETRY_LAST /* not used */
} retry = RETRY_NO;
long response;
if((CURLE_OPERATION_TIMEDOUT == result) ||
(CURLE_COULDNT_RESOLVE_HOST == result) ||
(CURLE_COULDNT_RESOLVE_PROXY == result) ||
(CURLE_FTP_ACCEPT_TIMEOUT == result))
/* retry timeout always */
retry = RETRY_TIMEOUT;
else if(config->retry_connrefused &&
(CURLE_COULDNT_CONNECT == result)) {
long oserrno;
curl_easy_getinfo(curl, CURLINFO_OS_ERRNO, &oserrno);
if(ECONNREFUSED == oserrno)
retry = RETRY_CONNREFUSED;
}
else if((CURLE_OK == result) ||
(config->failonerror &&
(CURLE_HTTP_RETURNED_ERROR == result))) {
/* If it returned OK. _or_ failonerror was enabled and it
returned due to such an error, check for HTTP transient
errors to retry on. */
char *effective_url = NULL;
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
if(effective_url &&
checkprefix("http", effective_url)) {
/* This was HTTP(S) */
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
switch(response) {
case 408: /* Request Timeout */
case 500: /* Internal Server Error */
case 502: /* Bad Gateway */
case 503: /* Service Unavailable */
case 504: /* Gateway Timeout */
retry = RETRY_HTTP;
/*
* At this point, we have already written data to the output
* file (or terminal). If we write to a file, we must rewind
* or close/re-open the file so that the next attempt starts
* over from the beginning.
*/
break;
}
}
} /* if CURLE_OK */
else if(result) {
long protocol;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
curl_easy_getinfo(curl, CURLINFO_PROTOCOL, &protocol);
if((protocol == CURLPROTO_FTP || protocol == CURLPROTO_FTPS) &&
response / 100 == 4)
/*
* This is typically when the FTP server only allows a certain
* amount of users and we are not one of them. All 4xx codes
* are transient.
*/
retry = RETRY_FTP;
}
if(retry) {
static const char * const m[]={
NULL,
"timeout",
"connection refused",
"HTTP error",
"FTP error"
};
warnf(config->global, "Transient problem: %s "
"Will retry in %ld seconds. "
"%ld retries left.\n",
m[retry], retry_sleep/1000L, retry_numretries);
tool_go_sleep(retry_sleep);
retry_numretries--;
if(!config->retry_delay) {
retry_sleep *= 2;
if(retry_sleep > RETRY_SLEEP_MAX)
retry_sleep = RETRY_SLEEP_MAX;
}
if(outs.bytes && outs.filename && outs.stream) {
int rc;
/* We have written data to a output file, we truncate file
*/
if(!global->mute)
fprintf(global->errors, "Throwing away %"
CURL_FORMAT_CURL_OFF_T " bytes\n",
outs.bytes);
fflush(outs.stream);
/* truncate file at the position where we started appending */
#ifdef HAVE_FTRUNCATE
if(ftruncate(fileno(outs.stream), outs.init)) {
/* when truncate fails, we can't just append as then we'll
create something strange, bail out */
if(!global->mute)
fprintf(global->errors,
"failed to truncate, exiting\n");
result = CURLE_WRITE_ERROR;
goto quit_urls;
}
/* now seek to the end of the file, the position where we
just truncated the file in a large file-safe way */
rc = fseek(outs.stream, 0, SEEK_END);
#else
/* ftruncate is not available, so just reposition the file
to the location we would have truncated it. This won't
work properly with large files on 32-bit systems, but
most of those will have ftruncate. */
rc = fseek(outs.stream, (long)outs.init, SEEK_SET);
#endif
if(rc) {
if(!global->mute)
fprintf(global->errors,
"failed seeking to end of file, exiting\n");
result = CURLE_WRITE_ERROR;
goto quit_urls;
}
outs.bytes = 0; /* clear for next round */
}
continue; /* curl_easy_perform loop */
}
} /* if retry_numretries */
else if(metalink) {
/* Metalink: Decide to try the next resource or
not. Basically, we want to try the next resource if
download was not successful. */
long response;
if(CURLE_OK == result) {
char *effective_url = NULL;
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
if(effective_url &&
curl_strnequal(effective_url, "http", 4)) {
/* This was HTTP(S) */
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
if(response != 200 && response != 206) {
metalink_next_res = 1;
fprintf(global->errors,
"Metalink: fetching (%s) from (%s) FAILED "
"(HTTP status code %ld)\n",
mlfile->filename, this_url, response);
}
}
}
else {
metalink_next_res = 1;
fprintf(global->errors,
"Metalink: fetching (%s) from (%s) FAILED (%s)\n",
mlfile->filename, this_url,
(errorbuffer[0]) ?
errorbuffer : curl_easy_strerror(result));
}
}
if(metalink && !metalink_next_res)
fprintf(global->errors, "Metalink: fetching (%s) from (%s) OK\n",
mlfile->filename, this_url);
/* In all ordinary cases, just break out of loop here */
break; /* curl_easy_perform loop */
}
if((global->progressmode == CURL_PROGRESS_BAR) &&
progressbar.calls)
/* if the custom progress bar has been displayed, we output a
newline here */
fputs("\n", progressbar.out);
if(config->writeout)
ourWriteOut(curl, &outs, config->writeout);
/*
** Code within this loop may jump directly here to label 'show_error'
** in order to display an error message for CURLcode stored in 'res'
** variable and exit loop once that necessary writing and cleanup
** in label 'quit_urls' has been done.
*/
show_error:
#ifdef __VMS
if(is_vms_shell()) {
/* VMS DCL shell behavior */
if(!global->showerror)
vms_show = VMSSTS_HIDE;
}
else
#endif
if(config->synthetic_error) {
;
}
else if(result && global->showerror) {
fprintf(global->errors, "curl: (%d) %s\n", result, (errorbuffer[0]) ?
errorbuffer : curl_easy_strerror(result));
if(result == CURLE_PEER_FAILED_VERIFICATION)
fputs(CURL_CA_CERT_ERRORMSG, global->errors);
}
/* Fall through comment to 'quit_urls' label */
/*
** Upon error condition and always that a message has already been
** displayed, code within this loop may jump directly here to label
** 'quit_urls' otherwise it should jump to 'show_error' label above.
**
** When 'res' variable is _not_ CURLE_OK loop will exit once that
** all code following 'quit_urls' has been executed. Otherwise it
** will loop to the beginning from where it may exit if there are
** no more urls left.
*/
quit_urls:
/* Set file extended attributes */
if(!result && config->xattr && outs.fopened && outs.stream) {
int rc = fwrite_xattr(curl, fileno(outs.stream));
if(rc)
warnf(config->global, "Error setting extended attributes: %s\n",
strerror(errno));
}
/* Close the file */
if(outs.fopened && outs.stream) {
int rc = fclose(outs.stream);
if(!result && rc) {
/* something went wrong in the writing process */
result = CURLE_WRITE_ERROR;
fprintf(global->errors, "(%d) Failed writing body\n", result);
}
}
else if(!outs.s_isreg && outs.stream) {
/* Dump standard stream buffered data */
int rc = fflush(outs.stream);
if(!result && rc) {
/* something went wrong in the writing process */
result = CURLE_WRITE_ERROR;
fprintf(global->errors, "(%d) Failed writing body\n", result);
}
}
#ifdef __AMIGA__
if(!result && outs.s_isreg && outs.filename) {
/* Set the url (up to 80 chars) as comment for the file */
if(strlen(urlnode->url) > 78)
urlnode->url[79] = '\0';
SetComment(outs.filename, urlnode->url);
}
#endif
/* File time can only be set _after_ the file has been closed */
if(!result && config->remote_time && outs.s_isreg && outs.filename) {
/* Ask libcurl if we got a remote file time */
curl_off_t filetime = -1;
curl_easy_getinfo(curl, CURLINFO_FILETIME_T, &filetime);
setfiletime(filetime, outs.filename, config->global->errors);
}
#ifdef USE_METALINK
if(!metalink && config->use_metalink && result == CURLE_OK) {
int rv = parse_metalink(config, &outs, this_url);
if(rv == 0)
fprintf(config->global->errors, "Metalink: parsing (%s) OK\n",
this_url);
else if(rv == -1)
fprintf(config->global->errors, "Metalink: parsing (%s) FAILED\n",
this_url);
}
else if(metalink && result == CURLE_OK && !metalink_next_res) {
int rv = metalink_check_hash(global, mlfile, outs.filename);
if(rv == 0) {
metalink_next_res = 1;
}
}
#endif /* USE_METALINK */
/* No more business with this output struct */
if(outs.alloc_filename)
Curl_safefree(outs.filename);
#ifdef USE_METALINK
if(outs.metalink_parser)
metalink_parser_context_delete(outs.metalink_parser);
#endif /* USE_METALINK */
memset(&outs, 0, sizeof(struct OutStruct));
hdrcbdata.outs = NULL;
/* Free loop-local allocated memory and close loop-local opened fd */
Curl_safefree(outfile);
Curl_safefree(this_url);
if(infdopen)
close(infd);
if(metalink) {
/* Should exit if error is fatal. */
if(is_fatal_error(result)) {
break;
}
if(!metalink_next_res)
break;
mlres = mlres->next;
if(mlres == NULL)
break;
}
else if(urlnum > 1) {
/* when url globbing, exit loop upon critical error */
if(is_fatal_error(result))
break;
}
else if(result)
/* when not url globbing, exit loop upon any error */
break;
} /* loop to the next URL */
/* Free loop-local allocated memory */
Curl_safefree(uploadfile);
if(urls) {
/* Free list of remaining URLs */
glob_cleanup(urls);
urls = NULL;
}
if(infilenum > 1) {
/* when file globbing, exit loop upon critical error */
if(is_fatal_error(result))
break;
}
else if(result)
/* when not file globbing, exit loop upon any error */
break;
} /* loop to the next globbed upload file */
/* Free loop-local allocated memory */
Curl_safefree(outfiles);
if(inglob) {
/* Free list of globbed upload files */
glob_cleanup(inglob);
inglob = NULL;
}
/* Free this URL node data without destroying the
the node itself nor modifying next pointer. */
Curl_safefree(urlnode->url);
Curl_safefree(urlnode->outfile);
Curl_safefree(urlnode->infile);
urlnode->flags = 0;
/*
** Bail out upon critical errors or --fail-early
*/
if(is_fatal_error(result) || (result && global->fail_early))
goto quit_curl;
} /* for-loop through all URLs */
/*
** Nested loops end here.
*/
quit_curl:
/* Reset the global config variables */
global->noprogress = orig_noprogress;
global->isatty = orig_isatty;
/* Free function-local referenced allocated memory */
Curl_safefree(httpgetfields);
/* Free list of given URLs */
clean_getout(config);
hdrcbdata.heads = NULL;
/* Close function-local opened file descriptors */
if(heads.fopened && heads.stream)
fclose(heads.stream);
if(heads.alloc_filename)
Curl_safefree(heads.filename);
/* Release metalink related resources here */
clean_metalink(config);
return result;
}
CURLcode operate(struct GlobalConfig *config, int argc, argv_item_t argv[])
{
CURLcode result = CURLE_OK;
/* Setup proper locale from environment */
#ifdef HAVE_SETLOCALE
setlocale(LC_ALL, "");
#endif
/* Parse .curlrc if necessary */
if((argc == 1) ||
(!curl_strequal(argv[1], "-q") &&
!curl_strequal(argv[1], "--disable"))) {
parseconfig(NULL, config); /* ignore possible failure */
/* If we had no arguments then make sure a url was specified in .curlrc */
if((argc < 2) && (!config->first->url_list)) {
helpf(config->errors, NULL);
result = CURLE_FAILED_INIT;
}
}
if(!result) {
/* Parse the command line arguments */
ParameterError res = parse_args(config, argc, argv);
if(res) {
result = CURLE_OK;
/* Check if we were asked for the help */
if(res == PARAM_HELP_REQUESTED)
tool_help();
/* Check if we were asked for the manual */
else if(res == PARAM_MANUAL_REQUESTED)
hugehelp();
/* Check if we were asked for the version information */
else if(res == PARAM_VERSION_INFO_REQUESTED)
tool_version_info();
/* Check if we were asked to list the SSL engines */
else if(res == PARAM_ENGINES_REQUESTED)
tool_list_engines(config->easy);
else if(res == PARAM_LIBCURL_UNSUPPORTED_PROTOCOL)
result = CURLE_UNSUPPORTED_PROTOCOL;
else
result = CURLE_FAILED_INIT;
}
else {
#ifndef CURL_DISABLE_LIBCURL_OPTION
if(config->libcurl) {
/* Initialise the libcurl source output */
result = easysrc_init();
}
#endif
/* Perform the main operations */
if(!result) {
size_t count = 0;
struct OperationConfig *operation = config->first;
/* Get the required arguments for each operation */
while(!result && operation) {
result = get_args(operation, count++);
operation = operation->next;
}
/* Set the current operation pointer */
config->current = config->first;
/* Perform each operation */
while(!result && config->current) {
result = operate_do(config, config->current);
config->current = config->current->next;
if(config->current && config->current->easy)
curl_easy_reset(config->current->easy);
}
#ifndef CURL_DISABLE_LIBCURL_OPTION
if(config->libcurl) {
/* Cleanup the libcurl source output */
easysrc_cleanup();
/* Dump the libcurl code if previously enabled */
dumpeasysrc(config);
}
#endif
}
else
helpf(config->errors, "out of memory\n");
}
}
return result;
}
| YifuLiu/AliOS-Things | components/curl/src/tool_operate.c | C | apache-2.0 | 72,776 |
#ifndef HEADER_CURL_TOOL_OPERATE_H
#define HEADER_CURL_TOOL_OPERATE_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
CURLcode operate(struct GlobalConfig *config, int argc, argv_item_t argv[]);
#endif /* HEADER_CURL_TOOL_OPERATE_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_operate.h | C | apache-2.0 | 1,239 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#include "strcase.h"
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_cfgable.h"
#include "tool_convert.h"
#include "tool_doswin.h"
#include "tool_operhlp.h"
#include "tool_metalink.h"
#include "memdebug.h" /* keep this as LAST include */
void clean_getout(struct OperationConfig *config)
{
struct getout *next;
struct getout *node = config->url_list;
while(node) {
next = node->next;
Curl_safefree(node->url);
Curl_safefree(node->outfile);
Curl_safefree(node->infile);
Curl_safefree(node);
node = next;
}
config->url_list = NULL;
}
bool output_expected(const char *url, const char *uploadfile)
{
if(!uploadfile)
return TRUE; /* download */
if(checkprefix("http://", url) || checkprefix("https://", url))
return TRUE; /* HTTP(S) upload */
return FALSE; /* non-HTTP upload, probably no output should be expected */
}
bool stdin_upload(const char *uploadfile)
{
return (!strcmp(uploadfile, "-") ||
!strcmp(uploadfile, ".")) ? TRUE : FALSE;
}
/*
* Adds the file name to the URL if it doesn't already have one.
* url will be freed before return if the returned pointer is different
*/
char *add_file_name_to_url(CURL *curl, char *url, const char *filename)
{
/* If no file name part is given in the URL, we add this file name */
char *ptr = strstr(url, "://");
if(ptr)
ptr += 3;
else
ptr = url;
ptr = strrchr(ptr, '/');
if(!ptr || !strlen(++ptr)) {
/* The URL has no file name part, add the local file name. In order
to be able to do so, we have to create a new URL in another
buffer.*/
/* We only want the part of the local path that is on the right
side of the rightmost slash and backslash. */
const char *filep = strrchr(filename, '/');
char *file2 = strrchr(filep?filep:filename, '\\');
char *encfile;
if(file2)
filep = file2 + 1;
else if(filep)
filep++;
else
filep = filename;
/* URL encode the file name */
encfile = curl_easy_escape(curl, filep, 0 /* use strlen */);
if(encfile) {
char *urlbuffer;
if(ptr)
/* there is a trailing slash on the URL */
urlbuffer = aprintf("%s%s", url, encfile);
else
/* there is no trailing slash on the URL */
urlbuffer = aprintf("%s/%s", url, encfile);
curl_free(encfile);
Curl_safefree(url);
if(!urlbuffer)
return NULL;
url = urlbuffer; /* use our new URL instead! */
}
else
Curl_safefree(url);
}
return url;
}
/* Extracts the name portion of the URL.
* Returns a pointer to a heap-allocated string or NULL if
* no name part, at location indicated by first argument.
*/
CURLcode get_url_file_name(char **filename, const char *url)
{
const char *pc, *pc2;
*filename = NULL;
/* Find and get the remote file name */
pc = strstr(url, "://");
if(pc)
pc += 3;
else
pc = url;
pc2 = strrchr(pc, '\\');
pc = strrchr(pc, '/');
if(pc2 && (!pc || pc < pc2))
pc = pc2;
if(pc)
/* duplicate the string beyond the slash */
pc++;
else
/* no slash => empty string */
pc = "";
*filename = strdup(pc);
if(!*filename)
return CURLE_OUT_OF_MEMORY;
#if defined(MSDOS) || defined(WIN32)
{
char *sanitized;
SANITIZEcode sc = sanitize_file_name(&sanitized, *filename, 0);
Curl_safefree(*filename);
if(sc)
return CURLE_URL_MALFORMAT;
*filename = sanitized;
}
#endif /* MSDOS || WIN32 */
/* in case we built debug enabled, we allow an environment variable
* named CURL_TESTDIR to prefix the given file name to put it into a
* specific directory
*/
#ifdef DEBUGBUILD
{
char *tdir = curlx_getenv("CURL_TESTDIR");
if(tdir) {
char buffer[512]; /* suitably large */
msnprintf(buffer, sizeof(buffer), "%s/%s", tdir, *filename);
Curl_safefree(*filename);
*filename = strdup(buffer); /* clone the buffer */
curl_free(tdir);
if(!*filename)
return CURLE_OUT_OF_MEMORY;
}
}
#endif
return CURLE_OK;
}
| YifuLiu/AliOS-Things | components/curl/src/tool_operhlp.c | C | apache-2.0 | 5,155 |
#ifndef HEADER_CURL_TOOL_OPERHLP_H
#define HEADER_CURL_TOOL_OPERHLP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
struct OperationConfig;
void clean_getout(struct OperationConfig *config);
bool output_expected(const char *url, const char *uploadfile);
bool stdin_upload(const char *uploadfile);
char *add_file_name_to_url(CURL *curl, char *url, const char *filename);
CURLcode get_url_file_name(char **filename, const char *url);
#endif /* HEADER_CURL_TOOL_OPERHLP_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_operhlp.h | C | apache-2.0 | 1,483 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#if defined(__SYMBIAN32__) || defined(NETWARE)
#ifdef NETWARE
# ifdef __NOVELL_LIBC__
# include <screen.h>
# else
# include <nwconio.h>
# endif
#endif
#include "tool_panykey.h"
#include "memdebug.h" /* keep this as LAST include */
void tool_pressanykey(void)
{
#if defined(__SYMBIAN32__)
getchar();
#elif defined(NETWARE)
pressanykey();
#endif
}
#endif /* __SYMBIAN32__ || NETWARE */
| YifuLiu/AliOS-Things | components/curl/src/tool_panykey.c | C | apache-2.0 | 1,453 |
#ifndef HEADER_CURL_TOOL_PANYKEY_H
#define HEADER_CURL_TOOL_PANYKEY_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#if defined(__SYMBIAN32__) || defined(NETWARE)
void tool_pressanykey(void);
#else
#define tool_pressanykey() Curl_nop_stmt
#endif
#endif /* HEADER_CURL_TOOL_PANYKEY_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_panykey.h | C | apache-2.0 | 1,296 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#include "strcase.h"
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_cfgable.h"
#include "tool_getparam.h"
#include "tool_getpass.h"
#include "tool_homedir.h"
#include "tool_msgs.h"
#include "tool_paramhlp.h"
#include "tool_version.h"
#include "memdebug.h" /* keep this as LAST include */
struct getout *new_getout(struct OperationConfig *config)
{
struct getout *node = calloc(1, sizeof(struct getout));
struct getout *last = config->url_last;
if(node) {
/* append this new node last in the list */
if(last)
last->next = node;
else
config->url_list = node; /* first node */
/* move the last pointer */
config->url_last = node;
node->flags = config->default_node_flags;
}
return node;
}
ParameterError file2string(char **bufp, FILE *file)
{
char *ptr;
char *string = NULL;
if(file) {
char buffer[256];
size_t stringlen = 0;
while(fgets(buffer, sizeof(buffer), file)) {
size_t buflen;
ptr = strchr(buffer, '\r');
if(ptr)
*ptr = '\0';
ptr = strchr(buffer, '\n');
if(ptr)
*ptr = '\0';
buflen = strlen(buffer);
ptr = realloc(string, stringlen + buflen + 1);
if(!ptr) {
Curl_safefree(string);
return PARAM_NO_MEM;
}
string = ptr;
strcpy(string + stringlen, buffer);
stringlen += buflen;
}
}
*bufp = string;
return PARAM_OK;
}
ParameterError file2memory(char **bufp, size_t *size, FILE *file)
{
char *newbuf;
char *buffer = NULL;
size_t nused = 0;
if(file) {
size_t nread;
size_t alloc = 512;
do {
if(!buffer || (alloc == nused)) {
/* size_t overflow detection for huge files */
if(alloc + 1 > ((size_t)-1)/2) {
Curl_safefree(buffer);
return PARAM_NO_MEM;
}
alloc *= 2;
/* allocate an extra char, reserved space, for null termination */
newbuf = realloc(buffer, alloc + 1);
if(!newbuf) {
Curl_safefree(buffer);
return PARAM_NO_MEM;
}
buffer = newbuf;
}
nread = fread(buffer + nused, 1, alloc-nused, file);
nused += nread;
} while(nread);
/* null terminate the buffer in case it's used as a string later */
buffer[nused] = '\0';
/* free trailing slack space, if possible */
if(alloc != nused) {
newbuf = realloc(buffer, nused + 1);
if(!newbuf) {
Curl_safefree(buffer);
return PARAM_NO_MEM;
}
buffer = newbuf;
}
/* discard buffer if nothing was read */
if(!nused) {
Curl_safefree(buffer); /* no string */
buffer = NULL;
}
}
*size = nused;
*bufp = buffer;
return PARAM_OK;
}
void cleanarg(char *str)
{
#ifdef HAVE_WRITABLE_ARGV
/* now that GetStr has copied the contents of nextarg, wipe the next
* argument out so that the username:password isn't displayed in the
* system process list */
if(str) {
size_t len = strlen(str);
memset(str, ' ', len);
}
#else
(void)str;
#endif
}
/*
* Parse the string and write the long in the given address. Return PARAM_OK
* on success, otherwise a parameter specific error enum.
*
* Since this function gets called with the 'nextarg' pointer from within the
* getparameter a lot, we must check it for NULL before accessing the str
* data.
*/
ParameterError str2num(long *val, const char *str)
{
if(str) {
char *endptr;
long num;
errno = 0;
num = strtol(str, &endptr, 10);
if(errno == ERANGE)
return PARAM_NUMBER_TOO_LARGE;
if((endptr != str) && (endptr == str + strlen(str))) {
*val = num;
return PARAM_OK; /* Ok */
}
}
return PARAM_BAD_NUMERIC; /* badness */
}
/*
* Parse the string and write the long in the given address. Return PARAM_OK
* on success, otherwise a parameter error enum. ONLY ACCEPTS POSITIVE NUMBERS!
*
* Since this function gets called with the 'nextarg' pointer from within the
* getparameter a lot, we must check it for NULL before accessing the str
* data.
*/
ParameterError str2unum(long *val, const char *str)
{
ParameterError result = str2num(val, str);
if(result != PARAM_OK)
return result;
if(*val < 0)
return PARAM_NEGATIVE_NUMERIC;
return PARAM_OK;
}
/*
* Parse the string and write the double in the given address. Return PARAM_OK
* on success, otherwise a parameter specific error enum.
*
* The 'max' argument is the maximum value allowed, as the numbers are often
* multiplied when later used.
*
* Since this function gets called with the 'nextarg' pointer from within the
* getparameter a lot, we must check it for NULL before accessing the str
* data.
*/
static ParameterError str2double(double *val, const char *str, long max)
{
if(str) {
char *endptr;
double num;
errno = 0;
num = strtod(str, &endptr);
if(errno == ERANGE)
return PARAM_NUMBER_TOO_LARGE;
if(num > max) {
/* too large */
return PARAM_NUMBER_TOO_LARGE;
}
if((endptr != str) && (endptr == str + strlen(str))) {
*val = num;
return PARAM_OK; /* Ok */
}
}
return PARAM_BAD_NUMERIC; /* badness */
}
/*
* Parse the string and write the double in the given address. Return PARAM_OK
* on success, otherwise a parameter error enum. ONLY ACCEPTS POSITIVE NUMBERS!
*
* The 'max' argument is the maximum value allowed, as the numbers are often
* multiplied when later used.
*
* Since this function gets called with the 'nextarg' pointer from within the
* getparameter a lot, we must check it for NULL before accessing the str
* data.
*/
ParameterError str2udouble(double *valp, const char *str, long max)
{
double value;
ParameterError result = str2double(&value, str, max);
if(result != PARAM_OK)
return result;
if(value < 0)
return PARAM_NEGATIVE_NUMERIC;
*valp = value;
return PARAM_OK;
}
/*
* Parse the string and modify the long in the given address. Return
* non-zero on failure, zero on success.
*
* The string is a list of protocols
*
* Since this function gets called with the 'nextarg' pointer from within the
* getparameter a lot, we must check it for NULL before accessing the str
* data.
*/
long proto2num(struct OperationConfig *config, long *val, const char *str)
{
char *buffer;
const char *sep = ",";
char *token;
static struct sprotos {
const char *name;
long bit;
} const protos[] = {
{ "all", CURLPROTO_ALL },
{ "http", CURLPROTO_HTTP },
{ "https", CURLPROTO_HTTPS },
{ "ftp", CURLPROTO_FTP },
{ "ftps", CURLPROTO_FTPS },
{ "scp", CURLPROTO_SCP },
{ "sftp", CURLPROTO_SFTP },
{ "telnet", CURLPROTO_TELNET },
{ "ldap", CURLPROTO_LDAP },
{ "ldaps", CURLPROTO_LDAPS },
{ "dict", CURLPROTO_DICT },
{ "file", CURLPROTO_FILE },
{ "tftp", CURLPROTO_TFTP },
{ "imap", CURLPROTO_IMAP },
{ "imaps", CURLPROTO_IMAPS },
{ "pop3", CURLPROTO_POP3 },
{ "pop3s", CURLPROTO_POP3S },
{ "smtp", CURLPROTO_SMTP },
{ "smtps", CURLPROTO_SMTPS },
{ "rtsp", CURLPROTO_RTSP },
{ "gopher", CURLPROTO_GOPHER },
{ "smb", CURLPROTO_SMB },
{ "smbs", CURLPROTO_SMBS },
{ NULL, 0 }
};
if(!str)
return 1;
buffer = strdup(str); /* because strtok corrupts it */
if(!buffer)
return 1;
/* Allow strtok() here since this isn't used threaded */
/* !checksrc! disable BANNEDFUNC 2 */
for(token = strtok(buffer, sep);
token;
token = strtok(NULL, sep)) {
enum e_action { allow, deny, set } action = allow;
struct sprotos const *pp;
/* Process token modifiers */
while(!ISALNUM(*token)) { /* may be NULL if token is all modifiers */
switch (*token++) {
case '=':
action = set;
break;
case '-':
action = deny;
break;
case '+':
action = allow;
break;
default: /* Includes case of terminating NULL */
Curl_safefree(buffer);
return 1;
}
}
for(pp = protos; pp->name; pp++) {
if(curl_strequal(token, pp->name)) {
switch(action) {
case deny:
*val &= ~(pp->bit);
break;
case allow:
*val |= pp->bit;
break;
case set:
*val = pp->bit;
break;
}
break;
}
}
if(!(pp->name)) { /* unknown protocol */
/* If they have specified only this protocol, we say treat it as
if no protocols are allowed */
if(action == set)
*val = 0;
warnf(config->global, "unrecognized protocol '%s'\n", token);
}
}
Curl_safefree(buffer);
return 0;
}
/**
* Check if the given string is a protocol supported by libcurl
*
* @param str the protocol name
* @return PARAM_OK protocol supported
* @return PARAM_LIBCURL_UNSUPPORTED_PROTOCOL protocol not supported
* @return PARAM_REQUIRES_PARAMETER missing parameter
*/
int check_protocol(const char *str)
{
const char * const *pp;
const curl_version_info_data *curlinfo = curl_version_info(CURLVERSION_NOW);
if(!str)
return PARAM_REQUIRES_PARAMETER;
for(pp = curlinfo->protocols; *pp; pp++) {
if(curl_strequal(*pp, str))
return PARAM_OK;
}
return PARAM_LIBCURL_UNSUPPORTED_PROTOCOL;
}
/**
* Parses the given string looking for an offset (which may be a
* larger-than-integer value). The offset CANNOT be negative!
*
* @param val the offset to populate
* @param str the buffer containing the offset
* @return PARAM_OK if successful, a parameter specific error enum if failure.
*/
ParameterError str2offset(curl_off_t *val, const char *str)
{
char *endptr;
if(str[0] == '-')
/* offsets aren't negative, this indicates weird input */
return PARAM_NEGATIVE_NUMERIC;
#if(SIZEOF_CURL_OFF_T > SIZEOF_LONG)
{
CURLofft offt = curlx_strtoofft(str, &endptr, 0, val);
if(CURL_OFFT_FLOW == offt)
return PARAM_NUMBER_TOO_LARGE;
else if(CURL_OFFT_INVAL == offt)
return PARAM_BAD_NUMERIC;
}
#else
errno = 0;
*val = strtol(str, &endptr, 0);
if((*val == LONG_MIN || *val == LONG_MAX) && errno == ERANGE)
return PARAM_NUMBER_TOO_LARGE;
#endif
if((endptr != str) && (endptr == str + strlen(str)))
return PARAM_OK;
return PARAM_BAD_NUMERIC;
}
static CURLcode checkpasswd(const char *kind, /* for what purpose */
const size_t i, /* operation index */
const bool last, /* TRUE if last operation */
char **userpwd) /* pointer to allocated string */
{
char *psep;
char *osep;
if(!*userpwd)
return CURLE_OK;
/* Attempt to find the password separator */
psep = strchr(*userpwd, ':');
/* Attempt to find the options separator */
osep = strchr(*userpwd, ';');
if(!psep && **userpwd != ';') {
/* no password present, prompt for one */
char passwd[256] = "";
char prompt[256];
size_t passwdlen;
size_t userlen = strlen(*userpwd);
char *passptr;
if(osep)
*osep = '\0';
/* build a nice-looking prompt */
if(!i && last)
curlx_msnprintf(prompt, sizeof(prompt),
"Enter %s password for user '%s':",
kind, *userpwd);
else
curlx_msnprintf(prompt, sizeof(prompt),
"Enter %s password for user '%s' on URL #%zu:",
kind, *userpwd, i + 1);
/* get password */
getpass_r(prompt, passwd, sizeof(passwd));
passwdlen = strlen(passwd);
if(osep)
*osep = ';';
/* extend the allocated memory area to fit the password too */
passptr = realloc(*userpwd,
passwdlen + 1 + /* an extra for the colon */
userlen + 1); /* an extra for the zero */
if(!passptr)
return CURLE_OUT_OF_MEMORY;
/* append the password separated with a colon */
passptr[userlen] = ':';
memcpy(&passptr[userlen + 1], passwd, passwdlen + 1);
*userpwd = passptr;
}
return CURLE_OK;
}
ParameterError add2list(struct curl_slist **list, const char *ptr)
{
struct curl_slist *newlist = curl_slist_append(*list, ptr);
if(newlist)
*list = newlist;
else
return PARAM_NO_MEM;
return PARAM_OK;
}
int ftpfilemethod(struct OperationConfig *config, const char *str)
{
if(curl_strequal("singlecwd", str))
return CURLFTPMETHOD_SINGLECWD;
if(curl_strequal("nocwd", str))
return CURLFTPMETHOD_NOCWD;
if(curl_strequal("multicwd", str))
return CURLFTPMETHOD_MULTICWD;
warnf(config->global, "unrecognized ftp file method '%s', using default\n",
str);
return CURLFTPMETHOD_MULTICWD;
}
int ftpcccmethod(struct OperationConfig *config, const char *str)
{
if(curl_strequal("passive", str))
return CURLFTPSSL_CCC_PASSIVE;
if(curl_strequal("active", str))
return CURLFTPSSL_CCC_ACTIVE;
warnf(config->global, "unrecognized ftp CCC method '%s', using default\n",
str);
return CURLFTPSSL_CCC_PASSIVE;
}
long delegation(struct OperationConfig *config, char *str)
{
if(curl_strequal("none", str))
return CURLGSSAPI_DELEGATION_NONE;
if(curl_strequal("policy", str))
return CURLGSSAPI_DELEGATION_POLICY_FLAG;
if(curl_strequal("always", str))
return CURLGSSAPI_DELEGATION_FLAG;
warnf(config->global, "unrecognized delegation method '%s', using none\n",
str);
return CURLGSSAPI_DELEGATION_NONE;
}
/*
* my_useragent: returns allocated string with default user agent
*/
static char *my_useragent(void)
{
return strdup(CURL_NAME "/" CURL_VERSION);
}
CURLcode get_args(struct OperationConfig *config, const size_t i)
{
CURLcode result = CURLE_OK;
bool last = (config->next ? FALSE : TRUE);
/* Check we have a password for the given host user */
if(config->userpwd && !config->oauth_bearer) {
result = checkpasswd("host", i, last, &config->userpwd);
if(result)
return result;
}
/* Check we have a password for the given proxy user */
if(config->proxyuserpwd) {
result = checkpasswd("proxy", i, last, &config->proxyuserpwd);
if(result)
return result;
}
/* Check we have a user agent */
if(!config->useragent) {
config->useragent = my_useragent();
if(!config->useragent) {
helpf(config->global->errors, "out of memory\n");
result = CURLE_OUT_OF_MEMORY;
}
}
return result;
}
/*
* Parse the string and modify ssl_version in the val argument. Return PARAM_OK
* on success, otherwise a parameter error enum. ONLY ACCEPTS POSITIVE NUMBERS!
*
* Since this function gets called with the 'nextarg' pointer from within the
* getparameter a lot, we must check it for NULL before accessing the str
* data.
*/
ParameterError str2tls_max(long *val, const char *str)
{
static struct s_tls_max {
const char *tls_max_str;
long tls_max;
} const tls_max_array[] = {
{ "default", CURL_SSLVERSION_MAX_DEFAULT },
{ "1.0", CURL_SSLVERSION_MAX_TLSv1_0 },
{ "1.1", CURL_SSLVERSION_MAX_TLSv1_1 },
{ "1.2", CURL_SSLVERSION_MAX_TLSv1_2 },
{ "1.3", CURL_SSLVERSION_MAX_TLSv1_3 }
};
size_t i = 0;
if(!str)
return PARAM_REQUIRES_PARAMETER;
for(i = 0; i < sizeof(tls_max_array)/sizeof(tls_max_array[0]); i++) {
if(!strcmp(str, tls_max_array[i].tls_max_str)) {
*val = tls_max_array[i].tls_max;
return PARAM_OK;
}
}
return PARAM_BAD_USE;
}
| YifuLiu/AliOS-Things | components/curl/src/tool_paramhlp.c | C | apache-2.0 | 16,479 |
#ifndef HEADER_CURL_TOOL_PARAMHLP_H
#define HEADER_CURL_TOOL_PARAMHLP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
struct getout *new_getout(struct OperationConfig *config);
ParameterError file2string(char **bufp, FILE *file);
ParameterError file2memory(char **bufp, size_t *size, FILE *file);
void cleanarg(char *str);
ParameterError str2num(long *val, const char *str);
ParameterError str2unum(long *val, const char *str);
ParameterError str2udouble(double *val, const char *str, long max);
long proto2num(struct OperationConfig *config, long *val, const char *str);
int check_protocol(const char *str);
ParameterError str2offset(curl_off_t *val, const char *str);
CURLcode get_args(struct OperationConfig *config, const size_t i);
ParameterError add2list(struct curl_slist **list, const char *ptr);
int ftpfilemethod(struct OperationConfig *config, const char *str);
int ftpcccmethod(struct OperationConfig *config, const char *str);
long delegation(struct OperationConfig *config, char *str);
ParameterError str2tls_max(long *val, const char *str);
#endif /* HEADER_CURL_TOOL_PARAMHLP_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_paramhlp.h | C | apache-2.0 | 2,116 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_cfgable.h"
#include "tool_getparam.h"
#include "tool_helpers.h"
#include "tool_homedir.h"
#include "tool_msgs.h"
#include "tool_parsecfg.h"
#include "memdebug.h" /* keep this as LAST include */
#define CURLRC DOT_CHAR "curlrc"
/* only acknowledge colon or equals as separators if the option was not
specified with an initial dash! */
#define ISSEP(x,dash) (!dash && (((x) == '=') || ((x) == ':')))
static const char *unslashquote(const char *line, char *param);
static char *my_get_line(FILE *fp);
/* return 0 on everything-is-fine, and non-zero otherwise */
int parseconfig(const char *filename, struct GlobalConfig *global)
{
FILE *file;
char filebuffer[512];
bool usedarg = FALSE;
int rc = 0;
struct OperationConfig *operation = global->first;
if(!filename || !*filename) {
/* NULL or no file name attempts to load .curlrc from the homedir! */
#ifndef __AMIGA__
char *home = homedir(); /* portable homedir finder */
filename = CURLRC; /* sensible default */
if(home) {
if(strlen(home) < (sizeof(filebuffer) - strlen(CURLRC))) {
msnprintf(filebuffer, sizeof(filebuffer),
"%s%s%s", home, DIR_CHAR, CURLRC);
#ifdef WIN32
/* Check if the file exists - if not, try CURLRC in the same
* directory as our executable
*/
file = fopen(filebuffer, FOPEN_READTEXT);
if(file != NULL) {
fclose(file);
filename = filebuffer;
}
else {
/* Get the filename of our executable. GetModuleFileName is
* already declared via inclusions done in setup header file.
* We assume that we are using the ASCII version here.
*/
int n = GetModuleFileNameA(0, filebuffer, sizeof(filebuffer));
if(n > 0 && n < (int)sizeof(filebuffer)) {
/* We got a valid filename - get the directory part */
char *lastdirchar = strrchr(filebuffer, '\\');
if(lastdirchar) {
size_t remaining;
*lastdirchar = 0;
/* If we have enough space, build the RC filename */
remaining = sizeof(filebuffer) - strlen(filebuffer);
if(strlen(CURLRC) < remaining - 1) {
msnprintf(lastdirchar, remaining,
"%s%s", DIR_CHAR, CURLRC);
/* Don't bother checking if it exists - we do that later */
filename = filebuffer;
}
}
}
}
#else /* WIN32 */
filename = filebuffer;
#endif /* WIN32 */
}
Curl_safefree(home); /* we've used it, now free it */
}
# else /* __AMIGA__ */
/* On AmigaOS all the config files are into env:
*/
filename = "ENV:" CURLRC;
#endif
}
if(strcmp(filename, "-"))
file = fopen(filename, FOPEN_READTEXT);
else
file = stdin;
if(file) {
char *line;
char *aline;
char *option;
char *param;
int lineno = 0;
bool dashed_option;
while(NULL != (aline = my_get_line(file))) {
int res;
bool alloced_param = FALSE;
lineno++;
line = aline;
/* line with # in the first non-blank column is a comment! */
while(*line && ISSPACE(*line))
line++;
switch(*line) {
case '#':
case '/':
case '\r':
case '\n':
case '*':
case '\0':
Curl_safefree(aline);
continue;
}
/* the option keywords starts here */
option = line;
/* the option starts with a dash? */
dashed_option = option[0]=='-'?TRUE:FALSE;
while(*line && !ISSPACE(*line) && !ISSEP(*line, dashed_option))
line++;
/* ... and has ended here */
if(*line)
*line++ = '\0'; /* zero terminate, we have a local copy of the data */
#ifdef DEBUG_CONFIG
fprintf(stderr, "GOT: %s\n", option);
#endif
/* pass spaces and separator(s) */
while(*line && (ISSPACE(*line) || ISSEP(*line, dashed_option)))
line++;
/* the parameter starts here (unless quoted) */
if(*line == '\"') {
/* quoted parameter, do the quote dance */
line++;
param = malloc(strlen(line) + 1); /* parameter */
if(!param) {
/* out of memory */
Curl_safefree(aline);
rc = 1;
break;
}
alloced_param = TRUE;
(void)unslashquote(line, param);
}
else {
param = line; /* parameter starts here */
while(*line && !ISSPACE(*line))
line++;
if(*line) {
*line = '\0'; /* zero terminate */
/* to detect mistakes better, see if there's data following */
line++;
/* pass all spaces */
while(*line && ISSPACE(*line))
line++;
switch(*line) {
case '\0':
case '\r':
case '\n':
case '#': /* comment */
break;
default:
warnf(operation->global, "%s:%d: warning: '%s' uses unquoted "
"white space in the line that may cause side-effects!\n",
filename, lineno, option);
}
}
if(!*param)
/* do this so getparameter can check for required parameters.
Otherwise it always thinks there's a parameter. */
param = NULL;
}
#ifdef DEBUG_CONFIG
fprintf(stderr, "PARAM: \"%s\"\n",(param ? param : "(null)"));
#endif
res = getparameter(option, param, &usedarg, global, operation);
if(!res && param && *param && !usedarg)
/* we passed in a parameter that wasn't used! */
res = PARAM_GOT_EXTRA_PARAMETER;
if(res == PARAM_NEXT_OPERATION) {
if(operation->url_list && operation->url_list->url) {
/* Allocate the next config */
operation->next = malloc(sizeof(struct OperationConfig));
if(operation->next) {
/* Initialise the newly created config */
config_init(operation->next);
/* Copy the easy handle */
operation->next->easy = global->easy;
/* Set the global config pointer */
operation->next->global = global;
/* Update the last operation pointer */
global->last = operation->next;
/* Move onto the new config */
operation->next->prev = operation;
operation = operation->next;
}
else
res = PARAM_NO_MEM;
}
}
if(res != PARAM_OK && res != PARAM_NEXT_OPERATION) {
/* the help request isn't really an error */
if(!strcmp(filename, "-")) {
filename = "<stdin>";
}
if(res != PARAM_HELP_REQUESTED &&
res != PARAM_MANUAL_REQUESTED &&
res != PARAM_VERSION_INFO_REQUESTED &&
res != PARAM_ENGINES_REQUESTED) {
const char *reason = param2text(res);
warnf(operation->global, "%s:%d: warning: '%s' %s\n",
filename, lineno, option, reason);
}
}
if(alloced_param)
Curl_safefree(param);
Curl_safefree(aline);
}
if(file != stdin)
fclose(file);
}
else
rc = 1; /* couldn't open the file */
return rc;
}
/*
* Copies the string from line to the buffer at param, unquoting
* backslash-quoted characters and NUL-terminating the output string.
* Stops at the first non-backslash-quoted double quote character or the
* end of the input string. param must be at least as long as the input
* string. Returns the pointer after the last handled input character.
*/
static const char *unslashquote(const char *line, char *param)
{
while(*line && (*line != '\"')) {
if(*line == '\\') {
char out;
line++;
/* default is to output the letter after the backslash */
switch(out = *line) {
case '\0':
continue; /* this'll break out of the loop */
case 't':
out = '\t';
break;
case 'n':
out = '\n';
break;
case 'r':
out = '\r';
break;
case 'v':
out = '\v';
break;
}
*param++ = out;
line++;
}
else
*param++ = *line++;
}
*param = '\0'; /* always zero terminate */
return line;
}
/*
* Reads a line from the given file, ensuring is NUL terminated.
* The pointer must be freed by the caller.
* NULL is returned on an out of memory condition.
*/
static char *my_get_line(FILE *fp)
{
char buf[4096];
char *nl = NULL;
char *line = NULL;
do {
if(NULL == fgets(buf, sizeof(buf), fp))
break;
if(!line) {
line = strdup(buf);
if(!line)
return NULL;
}
else {
char *ptr;
size_t linelen = strlen(line);
ptr = realloc(line, linelen + strlen(buf) + 1);
if(!ptr) {
Curl_safefree(line);
return NULL;
}
line = ptr;
strcpy(&line[linelen], buf);
}
nl = strchr(line, '\n');
} while(!nl);
if(nl)
*nl = '\0';
return line;
}
| YifuLiu/AliOS-Things | components/curl/src/tool_parsecfg.c | C | apache-2.0 | 10,193 |
#ifndef HEADER_CURL_TOOL_PARSECFG_H
#define HEADER_CURL_TOOL_PARSECFG_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
int parseconfig(const char *filename, struct GlobalConfig *config);
#endif /* HEADER_CURL_TOOL_PARSECFG_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_parsecfg.h | C | apache-2.0 | 1,233 |
#ifndef HEADER_CURL_TOOL_SDECLS_H
#define HEADER_CURL_TOOL_SDECLS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#ifdef USE_METALINK
# include <metalink/metalink.h>
#endif /* USE_METALINK */
/*
* OutStruct variables keep track of information relative to curl's
* output writing, which may take place to a standard stream or a file.
*
* 'filename' member is either a pointer to a file name string or NULL
* when dealing with a standard stream.
*
* 'alloc_filename' member is TRUE when string pointed by 'filename' has been
* dynamically allocated and 'belongs' to this OutStruct, otherwise FALSE.
*
* 'is_cd_filename' member is TRUE when string pointed by 'filename' has been
* set using a server-specified Content-Disposition filename, otherwise FALSE.
*
* 's_isreg' member is TRUE when output goes to a regular file, this also
* implies that output is 'seekable' and 'appendable' and also that member
* 'filename' points to file name's string. For any standard stream member
* 's_isreg' will be FALSE.
*
* 'fopened' member is TRUE when output goes to a regular file and it
* has been fopen'ed, requiring it to be closed later on. In any other
* case this is FALSE.
*
* 'stream' member is a pointer to a stream controlling object as returned
* from a 'fopen' call or a standard stream.
*
* 'config' member is a pointer to associated 'OperationConfig' struct.
*
* 'bytes' member represents amount written so far.
*
* 'init' member holds original file size or offset at which truncation is
* taking place. Always zero unless appending to a non-empty regular file.
*
* 'metalink_parser' member is a pointer to Metalink XML parser
* context.
*/
struct OutStruct {
char *filename;
bool alloc_filename;
bool is_cd_filename;
bool s_isreg;
bool fopened;
FILE *stream;
struct OperationConfig *config;
curl_off_t bytes;
curl_off_t init;
#ifdef USE_METALINK
metalink_parser_context_t *metalink_parser;
#endif /* USE_METALINK */
};
/*
* InStruct variables keep track of information relative to curl's
* input reading, which may take place from stdin or from some file.
*
* 'fd' member is either 'stdin' file descriptor number STDIN_FILENO
* or a file descriptor as returned from an 'open' call for some file.
*
* 'config' member is a pointer to associated 'OperationConfig' struct.
*/
struct InStruct {
int fd;
struct OperationConfig *config;
};
/*
* A linked list of these 'getout' nodes contain URL's to fetch,
* as well as information relative to where URL contents should
* be stored or which file should be uploaded.
*/
struct getout {
struct getout *next; /* next one */
char *url; /* the URL we deal with */
char *outfile; /* where to store the output */
char *infile; /* file to upload, if GETOUT_UPLOAD is set */
int flags; /* options - composed of GETOUT_* bits */
};
#define GETOUT_OUTFILE (1<<0) /* set when outfile is deemed done */
#define GETOUT_URL (1<<1) /* set when URL is deemed done */
#define GETOUT_USEREMOTE (1<<2) /* use remote file name locally */
#define GETOUT_UPLOAD (1<<3) /* if set, -T has been used */
#define GETOUT_NOUPLOAD (1<<4) /* if set, -T "" has been used */
#define GETOUT_METALINK (1<<5) /* set when Metalink download */
/*
* 'trace' enumeration represents curl's output look'n feel possibilities.
*/
typedef enum {
TRACE_NONE, /* no trace/verbose output at all */
TRACE_BIN, /* tcpdump inspired look */
TRACE_ASCII, /* like *BIN but without the hex output */
TRACE_PLAIN /* -v/--verbose type */
} trace;
/*
* 'HttpReq' enumeration represents HTTP request types.
*/
typedef enum {
HTTPREQ_UNSPEC, /* first in list */
HTTPREQ_GET,
HTTPREQ_HEAD,
HTTPREQ_MIMEPOST,
HTTPREQ_SIMPLEPOST
} HttpReq;
/*
* Complete struct declarations which have OperationConfig struct members,
* just in case this header is directly included in some source file.
*/
#include "tool_cfgable.h"
#endif /* HEADER_CURL_TOOL_SDECLS_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_sdecls.h | C | apache-2.0 | 5,052 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#ifndef CURL_DISABLE_LIBCURL_OPTION
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_cfgable.h"
#include "tool_easysrc.h"
#include "tool_setopt.h"
#include "tool_convert.h"
#include "memdebug.h" /* keep this as LAST include */
/* Lookup tables for converting setopt values back to symbols */
/* For enums, values may be in any order. */
/* For bit masks, put combinations first, then single bits, */
/* and finally any "NONE" value. */
#define NV(e) {#e, e}
#define NV1(e, v) {#e, (v)}
#define NVEND {NULL, 0} /* sentinel to mark end of list */
const NameValue setopt_nv_CURLPROXY[] = {
NV(CURLPROXY_HTTP),
NV(CURLPROXY_HTTP_1_0),
NV(CURLPROXY_HTTPS),
NV(CURLPROXY_SOCKS4),
NV(CURLPROXY_SOCKS5),
NV(CURLPROXY_SOCKS4A),
NV(CURLPROXY_SOCKS5_HOSTNAME),
NVEND,
};
const NameValue setopt_nv_CURL_SOCKS_PROXY[] = {
NV(CURLPROXY_SOCKS4),
NV(CURLPROXY_SOCKS5),
NV(CURLPROXY_SOCKS4A),
NV(CURLPROXY_SOCKS5_HOSTNAME),
NVEND,
};
const NameValueUnsigned setopt_nv_CURLAUTH[] = {
NV(CURLAUTH_ANY), /* combination */
NV(CURLAUTH_ANYSAFE), /* combination */
NV(CURLAUTH_BASIC),
NV(CURLAUTH_DIGEST),
NV(CURLAUTH_GSSNEGOTIATE),
NV(CURLAUTH_NTLM),
NV(CURLAUTH_DIGEST_IE),
NV(CURLAUTH_NTLM_WB),
NV(CURLAUTH_ONLY),
NV(CURLAUTH_NONE),
NVEND,
};
const NameValue setopt_nv_CURL_HTTP_VERSION[] = {
NV(CURL_HTTP_VERSION_NONE),
NV(CURL_HTTP_VERSION_1_0),
NV(CURL_HTTP_VERSION_1_1),
NV(CURL_HTTP_VERSION_2_0),
NV(CURL_HTTP_VERSION_2TLS),
NVEND,
};
const NameValue setopt_nv_CURL_SSLVERSION[] = {
NV(CURL_SSLVERSION_DEFAULT),
NV(CURL_SSLVERSION_TLSv1),
NV(CURL_SSLVERSION_SSLv2),
NV(CURL_SSLVERSION_SSLv3),
NV(CURL_SSLVERSION_TLSv1_0),
NV(CURL_SSLVERSION_TLSv1_1),
NV(CURL_SSLVERSION_TLSv1_2),
NV(CURL_SSLVERSION_TLSv1_3),
NVEND,
};
const NameValue setopt_nv_CURL_TIMECOND[] = {
NV(CURL_TIMECOND_IFMODSINCE),
NV(CURL_TIMECOND_IFUNMODSINCE),
NV(CURL_TIMECOND_LASTMOD),
NV(CURL_TIMECOND_NONE),
NVEND,
};
const NameValue setopt_nv_CURLFTPSSL_CCC[] = {
NV(CURLFTPSSL_CCC_NONE),
NV(CURLFTPSSL_CCC_PASSIVE),
NV(CURLFTPSSL_CCC_ACTIVE),
NVEND,
};
const NameValue setopt_nv_CURLUSESSL[] = {
NV(CURLUSESSL_NONE),
NV(CURLUSESSL_TRY),
NV(CURLUSESSL_CONTROL),
NV(CURLUSESSL_ALL),
NVEND,
};
const NameValueUnsigned setopt_nv_CURLSSLOPT[] = {
NV(CURLSSLOPT_ALLOW_BEAST),
NV(CURLSSLOPT_NO_REVOKE),
NVEND,
};
const NameValue setopt_nv_CURL_NETRC[] = {
NV(CURL_NETRC_IGNORED),
NV(CURL_NETRC_OPTIONAL),
NV(CURL_NETRC_REQUIRED),
NVEND,
};
/* These mappings essentially triplicated - see
* tool_libinfo.c and tool_paramhlp.c */
const NameValue setopt_nv_CURLPROTO[] = {
NV(CURLPROTO_ALL), /* combination */
NV(CURLPROTO_DICT),
NV(CURLPROTO_FILE),
NV(CURLPROTO_FTP),
NV(CURLPROTO_FTPS),
NV(CURLPROTO_GOPHER),
NV(CURLPROTO_HTTP),
NV(CURLPROTO_HTTPS),
NV(CURLPROTO_IMAP),
NV(CURLPROTO_IMAPS),
NV(CURLPROTO_LDAP),
NV(CURLPROTO_LDAPS),
NV(CURLPROTO_POP3),
NV(CURLPROTO_POP3S),
NV(CURLPROTO_RTSP),
NV(CURLPROTO_SCP),
NV(CURLPROTO_SFTP),
NV(CURLPROTO_SMB),
NV(CURLPROTO_SMBS),
NV(CURLPROTO_SMTP),
NV(CURLPROTO_SMTPS),
NV(CURLPROTO_TELNET),
NV(CURLPROTO_TFTP),
NVEND,
};
/* These options have non-zero default values. */
static const NameValue setopt_nv_CURLNONZERODEFAULTS[] = {
NV1(CURLOPT_SSL_VERIFYPEER, 1),
NV1(CURLOPT_SSL_VERIFYHOST, 1),
NV1(CURLOPT_SSL_ENABLE_NPN, 1),
NV1(CURLOPT_SSL_ENABLE_ALPN, 1),
NV1(CURLOPT_TCP_NODELAY, 1),
NV1(CURLOPT_PROXY_SSL_VERIFYPEER, 1),
NV1(CURLOPT_PROXY_SSL_VERIFYHOST, 1),
NV1(CURLOPT_SOCKS5_AUTH, 1),
NVEND
};
/* Format and add code; jump to nomem on malloc error */
#define ADD(args) do { \
ret = easysrc_add args; \
if(ret) \
goto nomem; \
} WHILE_FALSE
#define ADDF(args) do { \
ret = easysrc_addf args; \
if(ret) \
goto nomem; \
} WHILE_FALSE
#define NULL_CHECK(p) do { \
if(!p) { \
ret = CURLE_OUT_OF_MEMORY; \
goto nomem; \
} \
} WHILE_FALSE
#define DECL0(s) ADD((&easysrc_decl, s))
#define DECL1(f,a) ADDF((&easysrc_decl, f,a))
#define DATA0(s) ADD((&easysrc_data, s))
#define DATA1(f,a) ADDF((&easysrc_data, f,a))
#define DATA2(f,a,b) ADDF((&easysrc_data, f,a,b))
#define DATA3(f,a,b,c) ADDF((&easysrc_data, f,a,b,c))
#define CODE0(s) ADD((&easysrc_code, s))
#define CODE1(f,a) ADDF((&easysrc_code, f,a))
#define CODE2(f,a,b) ADDF((&easysrc_code, f,a,b))
#define CODE3(f,a,b,c) ADDF((&easysrc_code, f,a,b,c))
#define CLEAN0(s) ADD((&easysrc_clean, s))
#define CLEAN1(f,a) ADDF((&easysrc_clean, f,a))
#define REM0(s) ADD((&easysrc_toohard, s))
#define REM1(f,a) ADDF((&easysrc_toohard, f,a))
#define REM2(f,a,b) ADDF((&easysrc_toohard, f,a,b))
/* Escape string to C string syntax. Return NULL if out of memory.
* Is this correct for those wacky EBCDIC guys? */
static char *c_escape(const char *str, size_t len)
{
const char *s;
unsigned char c;
char *escaped, *e;
if(len == CURL_ZERO_TERMINATED)
len = strlen(str);
/* Check for possible overflow. */
if(len > (~(size_t) 0) / 4)
return NULL;
/* Allocate space based on worst-case */
escaped = malloc(4 * len + 1);
if(!escaped)
return NULL;
e = escaped;
for(s = str; (c = *s) != '\0'; s++) {
if(c == '\n') {
strcpy(e, "\\n");
e += 2;
}
else if(c == '\r') {
strcpy(e, "\\r");
e += 2;
}
else if(c == '\t') {
strcpy(e, "\\t");
e += 2;
}
else if(c == '\\') {
strcpy(e, "\\\\");
e += 2;
}
else if(c == '"') {
strcpy(e, "\\\"");
e += 2;
}
else if(! isprint(c)) {
msnprintf(e, 5, "\\%03o", (unsigned)c);
e += 4;
}
else
*e++ = c;
}
*e = '\0';
return escaped;
}
/* setopt wrapper for enum types */
CURLcode tool_setopt_enum(CURL *curl, struct GlobalConfig *config,
const char *name, CURLoption tag,
const NameValue *nvlist, long lval)
{
CURLcode ret = CURLE_OK;
bool skip = FALSE;
ret = curl_easy_setopt(curl, tag, lval);
if(!lval)
skip = TRUE;
if(config->libcurl && !skip && !ret) {
/* we only use this for real if --libcurl was used */
const NameValue *nv = NULL;
for(nv = nvlist; nv->name; nv++) {
if(nv->value == lval) break; /* found it */
}
if(! nv->name) {
/* If no definition was found, output an explicit value.
* This could happen if new values are defined and used
* but the NameValue list is not updated. */
CODE2("curl_easy_setopt(hnd, %s, %ldL);", name, lval);
}
else {
CODE2("curl_easy_setopt(hnd, %s, (long)%s);", name, nv->name);
}
}
nomem:
return ret;
}
/* setopt wrapper for flags */
CURLcode tool_setopt_flags(CURL *curl, struct GlobalConfig *config,
const char *name, CURLoption tag,
const NameValue *nvlist, long lval)
{
CURLcode ret = CURLE_OK;
bool skip = FALSE;
ret = curl_easy_setopt(curl, tag, lval);
if(!lval)
skip = TRUE;
if(config->libcurl && !skip && !ret) {
/* we only use this for real if --libcurl was used */
char preamble[80]; /* should accommodate any symbol name */
long rest = lval; /* bits not handled yet */
const NameValue *nv = NULL;
msnprintf(preamble, sizeof(preamble),
"curl_easy_setopt(hnd, %s, ", name);
for(nv = nvlist; nv->name; nv++) {
if((nv->value & ~ rest) == 0) {
/* all value flags contained in rest */
rest &= ~ nv->value; /* remove bits handled here */
CODE3("%s(long)%s%s",
preamble, nv->name, rest ? " |" : ");");
if(!rest)
break; /* handled them all */
/* replace with all spaces for continuation line */
msnprintf(preamble, sizeof(preamble), "%*s", strlen(preamble), "");
}
}
/* If any bits have no definition, output an explicit value.
* This could happen if new bits are defined and used
* but the NameValue list is not updated. */
if(rest)
CODE2("%s%ldL);", preamble, rest);
}
nomem:
return ret;
}
/* setopt wrapper for bitmasks */
CURLcode tool_setopt_bitmask(CURL *curl, struct GlobalConfig *config,
const char *name, CURLoption tag,
const NameValueUnsigned *nvlist,
long lval)
{
CURLcode ret = CURLE_OK;
bool skip = FALSE;
ret = curl_easy_setopt(curl, tag, lval);
if(!lval)
skip = TRUE;
if(config->libcurl && !skip && !ret) {
/* we only use this for real if --libcurl was used */
char preamble[80];
unsigned long rest = (unsigned long)lval;
const NameValueUnsigned *nv = NULL;
msnprintf(preamble, sizeof(preamble),
"curl_easy_setopt(hnd, %s, ", name);
for(nv = nvlist; nv->name; nv++) {
if((nv->value & ~ rest) == 0) {
/* all value flags contained in rest */
rest &= ~ nv->value; /* remove bits handled here */
CODE3("%s(long)%s%s",
preamble, nv->name, rest ? " |" : ");");
if(!rest)
break; /* handled them all */
/* replace with all spaces for continuation line */
msnprintf(preamble, sizeof(preamble), "%*s", strlen(preamble), "");
}
}
/* If any bits have no definition, output an explicit value.
* This could happen if new bits are defined and used
* but the NameValue list is not updated. */
if(rest)
CODE2("%s%luUL);", preamble, rest);
}
nomem:
return ret;
}
/* Generate code for a struct curl_slist. */
static CURLcode libcurl_generate_slist(struct curl_slist *slist, int *slistno)
{
CURLcode ret = CURLE_OK;
char *escaped = NULL;
/* May need several slist variables, so invent name */
*slistno = ++easysrc_slist_count;
DECL1("struct curl_slist *slist%d;", *slistno);
DATA1("slist%d = NULL;", *slistno);
CLEAN1("curl_slist_free_all(slist%d);", *slistno);
CLEAN1("slist%d = NULL;", *slistno);
for(; slist; slist = slist->next) {
Curl_safefree(escaped);
escaped = c_escape(slist->data, CURL_ZERO_TERMINATED);
if(!escaped)
return CURLE_OUT_OF_MEMORY;
DATA3("slist%d = curl_slist_append(slist%d, \"%s\");",
*slistno, *slistno, escaped);
}
nomem:
Curl_safefree(escaped);
return ret;
}
static CURLcode libcurl_generate_mime(CURL *curl,
struct GlobalConfig *config,
tool_mime *toolmime,
int *mimeno); /* Forward. */
/* Wrapper to generate source code for a mime part. */
static CURLcode libcurl_generate_mime_part(CURL *curl,
struct GlobalConfig *config,
tool_mime *part,
int mimeno)
{
CURLcode ret = CURLE_OK;
int submimeno = 0;
char *escaped = NULL;
const char *data = NULL;
const char *filename = part->filename;
/* Parts are linked in reverse order. */
if(part->prev) {
ret = libcurl_generate_mime_part(curl, config, part->prev, mimeno);
if(ret)
return ret;
}
/* Create the part. */
CODE2("part%d = curl_mime_addpart(mime%d);", mimeno, mimeno);
switch(part->kind) {
case TOOLMIME_PARTS:
ret = libcurl_generate_mime(curl, config, part, &submimeno);
if(!ret) {
CODE2("curl_mime_subparts(part%d, mime%d);", mimeno, submimeno);
CODE1("mime%d = NULL;", submimeno); /* Avoid freeing in CLEAN. */
}
break;
case TOOLMIME_DATA:
#ifdef CURL_DOES_CONVERSIONS
/* Data will be set in ASCII, thus issue a comment with clear text. */
escaped = c_escape(part->data, CURL_ZERO_TERMINATED);
NULL_CHECK(escaped);
CODE1("/* \"%s\" */", escaped);
/* Our data is always textual: convert it to ASCII. */
{
size_t size = strlen(part->data);
char *cp = malloc(size + 1);
NULL_CHECK(cp);
memcpy(cp, part->data, size + 1);
ret = convert_to_network(cp, size);
data = cp;
}
#else
data = part->data;
#endif
if(!ret) {
Curl_safefree(escaped);
escaped = c_escape(data, CURL_ZERO_TERMINATED);
NULL_CHECK(escaped);
CODE2("curl_mime_data(part%d, \"%s\", CURL_ZERO_TERMINATED);",
mimeno, escaped);
}
break;
case TOOLMIME_FILE:
case TOOLMIME_FILEDATA:
escaped = c_escape(part->data, CURL_ZERO_TERMINATED);
NULL_CHECK(escaped);
CODE2("curl_mime_filedata(part%d, \"%s\");", mimeno, escaped);
if(part->kind == TOOLMIME_FILEDATA && !filename) {
CODE1("curl_mime_filename(part%d, NULL);", mimeno);
}
break;
case TOOLMIME_STDIN:
if(!filename)
filename = "-";
/* FALLTHROUGH */
case TOOLMIME_STDINDATA:
/* Can only be reading stdin in the current context. */
CODE1("curl_mime_data_cb(part%d, -1, (curl_read_callback) fread, \\",
mimeno);
CODE0(" (curl_seek_callback) fseek, NULL, stdin);");
break;
default:
/* Other cases not possible in this context. */
break;
}
if(!ret && part->encoder) {
Curl_safefree(escaped);
escaped = c_escape(part->encoder, CURL_ZERO_TERMINATED);
NULL_CHECK(escaped);
CODE2("curl_mime_encoder(part%d, \"%s\");", mimeno, escaped);
}
if(!ret && filename) {
Curl_safefree(escaped);
escaped = c_escape(filename, CURL_ZERO_TERMINATED);
NULL_CHECK(escaped);
CODE2("curl_mime_filename(part%d, \"%s\");", mimeno, escaped);
}
if(!ret && part->name) {
Curl_safefree(escaped);
escaped = c_escape(part->name, CURL_ZERO_TERMINATED);
NULL_CHECK(escaped);
CODE2("curl_mime_name(part%d, \"%s\");", mimeno, escaped);
}
if(!ret && part->type) {
Curl_safefree(escaped);
escaped = c_escape(part->type, CURL_ZERO_TERMINATED);
NULL_CHECK(escaped);
CODE2("curl_mime_type(part%d, \"%s\");", mimeno, escaped);
}
if(!ret && part->headers) {
int slistno;
ret = libcurl_generate_slist(part->headers, &slistno);
if(!ret) {
CODE2("curl_mime_headers(part%d, slist%d, 1);", mimeno, slistno);
CODE1("slist%d = NULL;", slistno); /* Prevent CLEANing. */
}
}
nomem:
#ifdef CURL_DOES_CONVERSIONS
if(data)
free((char *) data);
#endif
Curl_safefree(escaped);
return ret;
}
/* Wrapper to generate source code for a mime structure. */
static CURLcode libcurl_generate_mime(CURL *curl,
struct GlobalConfig *config,
tool_mime *toolmime,
int *mimeno)
{
CURLcode ret = CURLE_OK;
/* May need several mime variables, so invent name. */
*mimeno = ++easysrc_mime_count;
DECL1("curl_mime *mime%d;", *mimeno);
DATA1("mime%d = NULL;", *mimeno);
CODE1("mime%d = curl_mime_init(hnd);", *mimeno);
CLEAN1("curl_mime_free(mime%d);", *mimeno);
CLEAN1("mime%d = NULL;", *mimeno);
if(toolmime->subparts) {
DECL1("curl_mimepart *part%d;", *mimeno);
ret = libcurl_generate_mime_part(curl, config,
toolmime->subparts, *mimeno);
}
nomem:
return ret;
}
/* setopt wrapper for CURLOPT_MIMEPOST */
CURLcode tool_setopt_mimepost(CURL *curl, struct GlobalConfig *config,
const char *name, CURLoption tag,
curl_mime *mimepost)
{
CURLcode ret = curl_easy_setopt(curl, tag, mimepost);
int mimeno = 0;
if(!ret && config->libcurl) {
ret = libcurl_generate_mime(curl, config,
config->current->mimeroot, &mimeno);
if(!ret)
CODE2("curl_easy_setopt(hnd, %s, mime%d);", name, mimeno);
}
nomem:
return ret;
}
/* setopt wrapper for curl_slist options */
CURLcode tool_setopt_slist(CURL *curl, struct GlobalConfig *config,
const char *name, CURLoption tag,
struct curl_slist *list)
{
CURLcode ret = CURLE_OK;
ret = curl_easy_setopt(curl, tag, list);
if(config->libcurl && list && !ret) {
int i;
ret = libcurl_generate_slist(list, &i);
if(!ret)
CODE2("curl_easy_setopt(hnd, %s, slist%d);", name, i);
}
nomem:
return ret;
}
/* generic setopt wrapper for all other options.
* Some type information is encoded in the tag value. */
CURLcode tool_setopt(CURL *curl, bool str, struct GlobalConfig *config,
const char *name, CURLoption tag, ...)
{
va_list arg;
char buf[256];
const char *value = NULL;
bool remark = FALSE;
bool skip = FALSE;
bool escape = FALSE;
char *escaped = NULL;
CURLcode ret = CURLE_OK;
va_start(arg, tag);
if(tag < CURLOPTTYPE_OBJECTPOINT) {
/* Value is expected to be a long */
long lval = va_arg(arg, long);
long defval = 0L;
const NameValue *nv = NULL;
for(nv = setopt_nv_CURLNONZERODEFAULTS; nv->name; nv++) {
if(!strcmp(name, nv->name)) {
defval = nv->value;
break; /* found it */
}
}
msnprintf(buf, sizeof(buf), "%ldL", lval);
value = buf;
ret = curl_easy_setopt(curl, tag, lval);
if(lval == defval)
skip = TRUE;
}
else if(tag < CURLOPTTYPE_OFF_T) {
/* Value is some sort of object pointer */
void *pval = va_arg(arg, void *);
/* function pointers are never printable */
if(tag >= CURLOPTTYPE_FUNCTIONPOINT) {
if(pval) {
value = "functionpointer";
remark = TRUE;
}
else
skip = TRUE;
}
else if(pval && str) {
value = (char *)pval;
escape = TRUE;
}
else if(pval) {
value = "objectpointer";
remark = TRUE;
}
else
skip = TRUE;
ret = curl_easy_setopt(curl, tag, pval);
}
else {
/* Value is expected to be curl_off_t */
curl_off_t oval = va_arg(arg, curl_off_t);
msnprintf(buf, sizeof(buf),
"(curl_off_t)%" CURL_FORMAT_CURL_OFF_T, oval);
value = buf;
ret = curl_easy_setopt(curl, tag, oval);
if(!oval)
skip = TRUE;
}
va_end(arg);
if(config->libcurl && !skip && !ret) {
/* we only use this for real if --libcurl was used */
if(remark)
REM2("%s set to a %s", name, value);
else {
if(escape) {
escaped = c_escape(value, CURL_ZERO_TERMINATED);
NULL_CHECK(escaped);
CODE2("curl_easy_setopt(hnd, %s, \"%s\");", name, escaped);
}
else
CODE2("curl_easy_setopt(hnd, %s, %s);", name, value);
}
}
nomem:
Curl_safefree(escaped);
return ret;
}
#endif /* CURL_DISABLE_LIBCURL_OPTION */
| YifuLiu/AliOS-Things | components/curl/src/tool_setopt.c | C | apache-2.0 | 19,793 |
#ifndef HEADER_CURL_TOOL_SETOPT_H
#define HEADER_CURL_TOOL_SETOPT_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#include "tool_formparse.h"
/*
* Macros used in operate()
*/
#define SETOPT_CHECK(v) do { \
result = (v); \
if(result) \
goto show_error; \
} WHILE_FALSE
#ifndef CURL_DISABLE_LIBCURL_OPTION
/* Associate symbolic names with option values */
typedef struct {
const char *name;
long value;
} NameValue;
typedef struct {
const char *name;
unsigned long value;
} NameValueUnsigned;
extern const NameValue setopt_nv_CURLPROXY[];
extern const NameValue setopt_nv_CURL_SOCKS_PROXY[];
extern const NameValue setopt_nv_CURL_HTTP_VERSION[];
extern const NameValue setopt_nv_CURL_SSLVERSION[];
extern const NameValue setopt_nv_CURL_TIMECOND[];
extern const NameValue setopt_nv_CURLFTPSSL_CCC[];
extern const NameValue setopt_nv_CURLUSESSL[];
extern const NameValueUnsigned setopt_nv_CURLSSLOPT[];
extern const NameValue setopt_nv_CURL_NETRC[];
extern const NameValue setopt_nv_CURLPROTO[];
extern const NameValueUnsigned setopt_nv_CURLAUTH[];
/* Map options to NameValue sets */
#define setopt_nv_CURLOPT_HTTP_VERSION setopt_nv_CURL_HTTP_VERSION
#define setopt_nv_CURLOPT_HTTPAUTH setopt_nv_CURLAUTH
#define setopt_nv_CURLOPT_SSLVERSION setopt_nv_CURL_SSLVERSION
#define setopt_nv_CURLOPT_PROXY_SSLVERSION setopt_nv_CURL_SSLVERSION
#define setopt_nv_CURLOPT_TIMECONDITION setopt_nv_CURL_TIMECOND
#define setopt_nv_CURLOPT_FTP_SSL_CCC setopt_nv_CURLFTPSSL_CCC
#define setopt_nv_CURLOPT_USE_SSL setopt_nv_CURLUSESSL
#define setopt_nv_CURLOPT_SSL_OPTIONS setopt_nv_CURLSSLOPT
#define setopt_nv_CURLOPT_NETRC setopt_nv_CURL_NETRC
#define setopt_nv_CURLOPT_PROTOCOLS setopt_nv_CURLPROTO
#define setopt_nv_CURLOPT_REDIR_PROTOCOLS setopt_nv_CURLPROTO
#define setopt_nv_CURLOPT_PROXYTYPE setopt_nv_CURLPROXY
#define setopt_nv_CURLOPT_PROXYAUTH setopt_nv_CURLAUTH
#define setopt_nv_CURLOPT_SOCKS5_AUTH setopt_nv_CURLAUTH
/* Intercept setopt calls for --libcurl */
CURLcode tool_setopt_enum(CURL *curl, struct GlobalConfig *config,
const char *name, CURLoption tag,
const NameValue *nv, long lval);
CURLcode tool_setopt_flags(CURL *curl, struct GlobalConfig *config,
const char *name, CURLoption tag,
const NameValue *nv, long lval);
CURLcode tool_setopt_bitmask(CURL *curl, struct GlobalConfig *config,
const char *name, CURLoption tag,
const NameValueUnsigned *nv, long lval);
CURLcode tool_setopt_mimepost(CURL *curl, struct GlobalConfig *config,
const char *name, CURLoption tag,
curl_mime *mimepost);
CURLcode tool_setopt_slist(CURL *curl, struct GlobalConfig *config,
const char *name, CURLoption tag,
struct curl_slist *list);
CURLcode tool_setopt(CURL *curl, bool str, struct GlobalConfig *config,
const char *name, CURLoption tag, ...);
#define my_setopt(x,y,z) \
SETOPT_CHECK(tool_setopt(x, FALSE, global, #y, y, z))
#define my_setopt_str(x,y,z) \
SETOPT_CHECK(tool_setopt(x, TRUE, global, #y, y, z))
#define my_setopt_enum(x,y,z) \
SETOPT_CHECK(tool_setopt_enum(x, global, #y, y, setopt_nv_ ## y, z))
#define my_setopt_flags(x,y,z) \
SETOPT_CHECK(tool_setopt_flags(x, global, #y, y, setopt_nv_ ## y, z))
#define my_setopt_bitmask(x,y,z) \
SETOPT_CHECK(tool_setopt_bitmask(x, global, #y, y, setopt_nv_ ## y, z))
#define my_setopt_mimepost(x,y,z) \
SETOPT_CHECK(tool_setopt_mimepost(x, global, #y, y, z))
#define my_setopt_slist(x,y,z) \
SETOPT_CHECK(tool_setopt_slist(x, global, #y, y, z))
#define res_setopt(x,y,z) tool_setopt(x, FALSE, global, #y, y, z)
#define res_setopt_str(x,y,z) tool_setopt(x, TRUE, global, #y, y, z)
#else /* CURL_DISABLE_LIBCURL_OPTION */
/* No --libcurl, so pass options directly to library */
#define my_setopt(x,y,z) \
SETOPT_CHECK(curl_easy_setopt(x, y, z))
#define my_setopt_str(x,y,z) \
SETOPT_CHECK(curl_easy_setopt(x, y, z))
#define my_setopt_enum(x,y,z) \
SETOPT_CHECK(curl_easy_setopt(x, y, z))
#define my_setopt_flags(x,y,z) \
SETOPT_CHECK(curl_easy_setopt(x, y, z))
#define my_setopt_bitmask(x,y,z) \
SETOPT_CHECK(curl_easy_setopt(x, y, z))
#define my_setopt_mimepost(x,y,z) \
SETOPT_CHECK(curl_easy_setopt(x, y, z))
#define my_setopt_slist(x,y,z) \
SETOPT_CHECK(curl_easy_setopt(x, y, z))
#define res_setopt(x,y,z) curl_easy_setopt(x,y,z)
#define res_setopt_str(x,y,z) curl_easy_setopt(x,y,z)
#endif /* CURL_DISABLE_LIBCURL_OPTION */
#endif /* HEADER_CURL_TOOL_SETOPT_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_setopt.h | C | apache-2.0 | 5,695 |
#ifndef HEADER_CURL_TOOL_SETUP_H
#define HEADER_CURL_TOOL_SETUP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#define CURL_NO_OLDIES
/*
* curl_setup.h may define preprocessor macros such as _FILE_OFFSET_BITS and
* _LARGE_FILES in order to support files larger than 2 GB. On platforms
* where this happens it is mandatory that these macros are defined before
* any system header file is included, otherwise file handling function
* prototypes will be misdeclared and curl tool may not build properly;
* therefore we must include curl_setup.h before curl.h when building curl.
*/
#include "curl_setup.h" /* from the lib directory */
/*
* curl tool certainly uses libcurl's external interface.
*/
#include <curl/curl.h> /* external interface */
/*
* Platform specific stuff.
*/
#if defined(macintosh) && defined(__MRC__)
# define main(x,y) curl_main(x,y)
#endif
#ifdef TPF
# undef select
/* change which select is used for the curl command line tool */
# define select(a,b,c,d,e) tpf_select_bsd(a,b,c,d,e)
/* and turn off the progress meter */
# define CONF_DEFAULT (0|CONF_NOPROGRESS)
#endif
#ifndef OS
# define OS "unknown"
#endif
#ifndef UNPRINTABLE_CHAR
/* define what to use for unprintable characters */
# define UNPRINTABLE_CHAR '.'
#endif
#ifndef HAVE_STRDUP
# include "tool_strdup.h"
#endif
#endif /* HEADER_CURL_TOOL_SETUP_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_setup.h | C | apache-2.0 | 2,356 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#ifdef HAVE_SYS_SELECT_H
# include <sys/select.h>
#endif
#ifdef HAVE_POLL_H
# include <poll.h>
#elif defined(HAVE_SYS_POLL_H)
# include <sys/poll.h>
#endif
#ifdef MSDOS
# include <dos.h>
#endif
#include "tool_sleep.h"
#include "memdebug.h" /* keep this as LAST include */
void tool_go_sleep(long ms)
{
#if defined(MSDOS)
delay(ms);
#elif defined(WIN32)
Sleep(ms);
#elif defined(HAVE_POLL_FINE)
(void)poll((void *)0, 0, (int)ms);
#else
struct timeval timeout;
timeout.tv_sec = ms / 1000L;
ms = ms % 1000L;
timeout.tv_usec = (int)ms * 1000;
select(0, NULL, NULL, NULL, &timeout);
#endif
}
| YifuLiu/AliOS-Things | components/curl/src/tool_sleep.c | C | apache-2.0 | 1,664 |
#ifndef HEADER_CURL_TOOL_SLEEP_H
#define HEADER_CURL_TOOL_SLEEP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
void tool_go_sleep(long ms);
#endif /* HEADER_CURL_TOOL_SLEEP_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_sleep.h | C | apache-2.0 | 1,185 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2015, 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_strdup.h"
#ifndef HAVE_STRDUP
char *strdup(const char *str)
{
size_t len;
char *newstr;
if(!str)
return (char *)NULL;
len = strlen(str);
if(len >= ((size_t)-1) / sizeof(char))
return (char *)NULL;
newstr = malloc((len + 1)*sizeof(char));
if(!newstr)
return (char *)NULL;
memcpy(newstr, str, (len + 1)*sizeof(char));
return newstr;
}
#endif
| YifuLiu/AliOS-Things | components/curl/src/tool_strdup.c | C | apache-2.0 | 1,425 |
#ifndef HEADER_TOOL_STRDUP_H
#define HEADER_TOOL_STRDUP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#ifndef HAVE_STRDUP
extern char *strdup(const char *str);
#endif
#endif /* HEADER_TOOL_STRDUP_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_strdup.h | C | apache-2.0 | 1,209 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_cfgable.h"
#include "tool_doswin.h"
#include "tool_urlglob.h"
#include "tool_vms.h"
#include "memdebug.h" /* keep this as LAST include */
#define GLOBERROR(string, column, code) \
glob->error = string, glob->pos = column, code
static CURLcode glob_fixed(URLGlob *glob, char *fixed, size_t len)
{
URLPattern *pat = &glob->pattern[glob->size];
pat->type = UPTSet;
pat->content.Set.size = 1;
pat->content.Set.ptr_s = 0;
pat->globindex = -1;
pat->content.Set.elements = malloc(sizeof(char *));
if(!pat->content.Set.elements)
return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
pat->content.Set.elements[0] = malloc(len + 1);
if(!pat->content.Set.elements[0])
return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
memcpy(pat->content.Set.elements[0], fixed, len);
pat->content.Set.elements[0][len] = 0;
return CURLE_OK;
}
/* multiply
*
* Multiplies and checks for overflow.
*/
static int multiply(unsigned long *amount, long with)
{
unsigned long sum = *amount * with;
if(!with) {
*amount = 0;
return 0;
}
if(sum/with != *amount)
return 1; /* didn't fit, bail out */
*amount = sum;
return 0;
}
static CURLcode glob_set(URLGlob *glob, char **patternp,
size_t *posp, unsigned long *amount,
int globindex)
{
/* processes a set expression with the point behind the opening '{'
','-separated elements are collected until the next closing '}'
*/
URLPattern *pat;
bool done = FALSE;
char *buf = glob->glob_buffer;
char *pattern = *patternp;
char *opattern = pattern;
size_t opos = *posp-1;
pat = &glob->pattern[glob->size];
/* patterns 0,1,2,... correspond to size=1,3,5,... */
pat->type = UPTSet;
pat->content.Set.size = 0;
pat->content.Set.ptr_s = 0;
pat->content.Set.elements = NULL;
pat->globindex = globindex;
while(!done) {
switch (*pattern) {
case '\0': /* URL ended while set was still open */
return GLOBERROR("unmatched brace", opos, CURLE_URL_MALFORMAT);
case '{':
case '[': /* no nested expressions at this time */
return GLOBERROR("nested brace", *posp, CURLE_URL_MALFORMAT);
case '}': /* set element completed */
if(opattern == pattern)
return GLOBERROR("empty string within braces", *posp,
CURLE_URL_MALFORMAT);
/* add 1 to size since it'll be incremented below */
if(multiply(amount, pat->content.Set.size + 1))
return GLOBERROR("range overflow", 0, CURLE_URL_MALFORMAT);
/* FALLTHROUGH */
case ',':
*buf = '\0';
if(pat->content.Set.elements) {
char **new_arr = realloc(pat->content.Set.elements,
(pat->content.Set.size + 1) * sizeof(char *));
if(!new_arr)
return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
pat->content.Set.elements = new_arr;
}
else
pat->content.Set.elements = malloc(sizeof(char *));
if(!pat->content.Set.elements)
return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
pat->content.Set.elements[pat->content.Set.size] =
strdup(glob->glob_buffer);
if(!pat->content.Set.elements[pat->content.Set.size])
return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
++pat->content.Set.size;
if(*pattern == '}') {
pattern++; /* pass the closing brace */
done = TRUE;
continue;
}
buf = glob->glob_buffer;
++pattern;
++(*posp);
break;
case ']': /* illegal closing bracket */
return GLOBERROR("unexpected close bracket", *posp, CURLE_URL_MALFORMAT);
case '\\': /* escaped character, skip '\' */
if(pattern[1]) {
++pattern;
++(*posp);
}
/* FALLTHROUGH */
default:
*buf++ = *pattern++; /* copy character to set element */
++(*posp);
}
}
*patternp = pattern; /* return with the new position */
return CURLE_OK;
}
static CURLcode glob_range(URLGlob *glob, char **patternp,
size_t *posp, unsigned long *amount,
int globindex)
{
/* processes a range expression with the point behind the opening '['
- char range: e.g. "a-z]", "B-Q]"
- num range: e.g. "0-9]", "17-2000]"
- num range with leading zeros: e.g. "001-999]"
expression is checked for well-formedness and collected until the next ']'
*/
URLPattern *pat;
int rc;
char *pattern = *patternp;
char *c;
pat = &glob->pattern[glob->size];
pat->globindex = globindex;
if(ISALPHA(*pattern)) {
/* character range detected */
char min_c;
char max_c;
char end_c;
unsigned long step = 1;
pat->type = UPTCharRange;
rc = sscanf(pattern, "%c-%c%c", &min_c, &max_c, &end_c);
if(rc == 3) {
if(end_c == ':') {
char *endp;
errno = 0;
step = strtoul(&pattern[4], &endp, 10);
if(errno || &pattern[4] == endp || *endp != ']')
step = 0;
else
pattern = endp + 1;
}
else if(end_c != ']')
/* then this is wrong */
rc = 0;
else
/* end_c == ']' */
pattern += 4;
}
*posp += (pattern - *patternp);
if(rc != 3 || !step || step > (unsigned)INT_MAX ||
(min_c == max_c && step != 1) ||
(min_c != max_c && (min_c > max_c || step > (unsigned)(max_c - min_c) ||
(max_c - min_c) > ('z' - 'a'))))
/* the pattern is not well-formed */
return GLOBERROR("bad range", *posp, CURLE_URL_MALFORMAT);
/* if there was a ":[num]" thing, use that as step or else use 1 */
pat->content.CharRange.step = (int)step;
pat->content.CharRange.ptr_c = pat->content.CharRange.min_c = min_c;
pat->content.CharRange.max_c = max_c;
if(multiply(amount, ((pat->content.CharRange.max_c -
pat->content.CharRange.min_c) /
pat->content.CharRange.step + 1)))
return GLOBERROR("range overflow", *posp, CURLE_URL_MALFORMAT);
}
else if(ISDIGIT(*pattern)) {
/* numeric range detected */
unsigned long min_n;
unsigned long max_n = 0;
unsigned long step_n = 0;
char *endp;
pat->type = UPTNumRange;
pat->content.NumRange.padlength = 0;
if(*pattern == '0') {
/* leading zero specified, count them! */
c = pattern;
while(ISDIGIT(*c)) {
c++;
++pat->content.NumRange.padlength; /* padding length is set for all
instances of this pattern */
}
}
errno = 0;
min_n = strtoul(pattern, &endp, 10);
if(errno || (endp == pattern))
endp = NULL;
else {
if(*endp != '-')
endp = NULL;
else {
pattern = endp + 1;
while(*pattern && ISBLANK(*pattern))
pattern++;
if(!ISDIGIT(*pattern)) {
endp = NULL;
goto fail;
}
errno = 0;
max_n = strtoul(pattern, &endp, 10);
if(errno)
/* overflow */
endp = NULL;
else if(*endp == ':') {
pattern = endp + 1;
errno = 0;
step_n = strtoul(pattern, &endp, 10);
if(errno)
/* over/underflow situation */
endp = NULL;
}
else
step_n = 1;
if(endp && (*endp == ']')) {
pattern = endp + 1;
}
else
endp = NULL;
}
}
fail:
*posp += (pattern - *patternp);
if(!endp || !step_n ||
(min_n == max_n && step_n != 1) ||
(min_n != max_n && (min_n > max_n || step_n > (max_n - min_n))))
/* the pattern is not well-formed */
return GLOBERROR("bad range", *posp, CURLE_URL_MALFORMAT);
/* typecasting to ints are fine here since we make sure above that we
are within 31 bits */
pat->content.NumRange.ptr_n = pat->content.NumRange.min_n = min_n;
pat->content.NumRange.max_n = max_n;
pat->content.NumRange.step = step_n;
if(multiply(amount, ((pat->content.NumRange.max_n -
pat->content.NumRange.min_n) /
pat->content.NumRange.step + 1)))
return GLOBERROR("range overflow", *posp, CURLE_URL_MALFORMAT);
}
else
return GLOBERROR("bad range specification", *posp, CURLE_URL_MALFORMAT);
*patternp = pattern;
return CURLE_OK;
}
static bool peek_ipv6(const char *str, size_t *skip)
{
/*
* Scan for a potential IPv6 literal.
* - Valid globs contain a hyphen and <= 1 colon.
* - IPv6 literals contain no hyphens and >= 2 colons.
*/
size_t i = 0;
size_t colons = 0;
if(str[i++] != '[') {
return FALSE;
}
for(;;) {
const char c = str[i++];
if(ISALNUM(c) || c == '.' || c == '%') {
/* ok */
}
else if(c == ':') {
colons++;
}
else if(c == ']') {
*skip = i;
return colons >= 2 ? TRUE : FALSE;
}
else {
return FALSE;
}
}
}
static CURLcode glob_parse(URLGlob *glob, char *pattern,
size_t pos, unsigned long *amount)
{
/* processes a literal string component of a URL
special characters '{' and '[' branch to set/range processing functions
*/
CURLcode res = CURLE_OK;
int globindex = 0; /* count "actual" globs */
*amount = 1;
while(*pattern && !res) {
char *buf = glob->glob_buffer;
size_t sublen = 0;
while(*pattern && *pattern != '{') {
if(*pattern == '[') {
/* skip over IPv6 literals and [] */
size_t skip = 0;
if(!peek_ipv6(pattern, &skip) && (pattern[1] == ']'))
skip = 2;
if(skip) {
memcpy(buf, pattern, skip);
buf += skip;
pattern += skip;
sublen += skip;
continue;
}
break;
}
if(*pattern == '}' || *pattern == ']')
return GLOBERROR("unmatched close brace/bracket", pos,
CURLE_URL_MALFORMAT);
/* only allow \ to escape known "special letters" */
if(*pattern == '\\' &&
(*(pattern + 1) == '{' || *(pattern + 1) == '[' ||
*(pattern + 1) == '}' || *(pattern + 1) == ']') ) {
/* escape character, skip '\' */
++pattern;
++pos;
}
*buf++ = *pattern++; /* copy character to literal */
++pos;
sublen++;
}
if(sublen) {
/* we got a literal string, add it as a single-item list */
*buf = '\0';
res = glob_fixed(glob, glob->glob_buffer, sublen);
}
else {
switch (*pattern) {
case '\0': /* done */
break;
case '{':
/* process set pattern */
pattern++;
pos++;
res = glob_set(glob, &pattern, &pos, amount, globindex++);
break;
case '[':
/* process range pattern */
pattern++;
pos++;
res = glob_range(glob, &pattern, &pos, amount, globindex++);
break;
}
}
if(++glob->size >= GLOB_PATTERN_NUM)
return GLOBERROR("too many globs", pos, CURLE_URL_MALFORMAT);
}
return res;
}
CURLcode glob_url(URLGlob **glob, char *url, unsigned long *urlnum,
FILE *error)
{
/*
* We can deal with any-size, just make a buffer with the same length
* as the specified URL!
*/
URLGlob *glob_expand;
unsigned long amount = 0;
char *glob_buffer;
CURLcode res;
*glob = NULL;
glob_buffer = malloc(strlen(url) + 1);
if(!glob_buffer)
return CURLE_OUT_OF_MEMORY;
glob_buffer[0] = 0;
glob_expand = calloc(1, sizeof(URLGlob));
if(!glob_expand) {
Curl_safefree(glob_buffer);
return CURLE_OUT_OF_MEMORY;
}
glob_expand->urllen = strlen(url);
glob_expand->glob_buffer = glob_buffer;
res = glob_parse(glob_expand, url, 1, &amount);
if(!res)
*urlnum = amount;
else {
if(error && glob_expand->error) {
char text[512];
const char *t;
if(glob_expand->pos) {
msnprintf(text, sizeof(text), "%s in URL position %zu:\n%s\n%*s^",
glob_expand->error,
glob_expand->pos, url, glob_expand->pos - 1, " ");
t = text;
}
else
t = glob_expand->error;
/* send error description to the error-stream */
fprintf(error, "curl: (%d) %s\n", res, t);
}
/* it failed, we cleanup */
glob_cleanup(glob_expand);
*urlnum = 1;
return res;
}
*glob = glob_expand;
return CURLE_OK;
}
void glob_cleanup(URLGlob* glob)
{
size_t i;
int elem;
for(i = 0; i < glob->size; i++) {
if((glob->pattern[i].type == UPTSet) &&
(glob->pattern[i].content.Set.elements)) {
for(elem = glob->pattern[i].content.Set.size - 1;
elem >= 0;
--elem) {
Curl_safefree(glob->pattern[i].content.Set.elements[elem]);
}
Curl_safefree(glob->pattern[i].content.Set.elements);
}
}
Curl_safefree(glob->glob_buffer);
Curl_safefree(glob);
}
CURLcode glob_next_url(char **globbed, URLGlob *glob)
{
URLPattern *pat;
size_t i;
size_t len;
size_t buflen = glob->urllen + 1;
char *buf = glob->glob_buffer;
*globbed = NULL;
if(!glob->beenhere)
glob->beenhere = 1;
else {
bool carry = TRUE;
/* implement a counter over the index ranges of all patterns, starting
with the rightmost pattern */
for(i = 0; carry && (i < glob->size); i++) {
carry = FALSE;
pat = &glob->pattern[glob->size - 1 - i];
switch(pat->type) {
case UPTSet:
if((pat->content.Set.elements) &&
(++pat->content.Set.ptr_s == pat->content.Set.size)) {
pat->content.Set.ptr_s = 0;
carry = TRUE;
}
break;
case UPTCharRange:
pat->content.CharRange.ptr_c =
(char)(pat->content.CharRange.step +
(int)((unsigned char)pat->content.CharRange.ptr_c));
if(pat->content.CharRange.ptr_c > pat->content.CharRange.max_c) {
pat->content.CharRange.ptr_c = pat->content.CharRange.min_c;
carry = TRUE;
}
break;
case UPTNumRange:
pat->content.NumRange.ptr_n += pat->content.NumRange.step;
if(pat->content.NumRange.ptr_n > pat->content.NumRange.max_n) {
pat->content.NumRange.ptr_n = pat->content.NumRange.min_n;
carry = TRUE;
}
break;
default:
printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
return CURLE_FAILED_INIT;
}
}
if(carry) { /* first pattern ptr has run into overflow, done! */
return CURLE_OK;
}
}
for(i = 0; i < glob->size; ++i) {
pat = &glob->pattern[i];
switch(pat->type) {
case UPTSet:
if(pat->content.Set.elements) {
msnprintf(buf, buflen, "%s",
pat->content.Set.elements[pat->content.Set.ptr_s]);
len = strlen(buf);
buf += len;
buflen -= len;
}
break;
case UPTCharRange:
if(buflen) {
*buf++ = pat->content.CharRange.ptr_c;
*buf = '\0';
buflen--;
}
break;
case UPTNumRange:
msnprintf(buf, buflen, "%0*lu",
pat->content.NumRange.padlength,
pat->content.NumRange.ptr_n);
len = strlen(buf);
buf += len;
buflen -= len;
break;
default:
printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
return CURLE_FAILED_INIT;
}
}
*globbed = strdup(glob->glob_buffer);
if(!*globbed)
return CURLE_OUT_OF_MEMORY;
return CURLE_OK;
}
CURLcode glob_match_url(char **result, char *filename, URLGlob *glob)
{
char *target;
size_t allocsize;
char numbuf[18];
char *appendthis = (char *)"";
size_t appendlen = 0;
size_t stringlen = 0;
*result = NULL;
/* We cannot use the glob_buffer for storage here since the filename may
* be longer than the URL we use. We allocate a good start size, then
* we need to realloc in case of need.
*/
allocsize = strlen(filename) + 1; /* make it at least one byte to store the
trailing zero */
target = malloc(allocsize);
if(!target)
return CURLE_OUT_OF_MEMORY;
while(*filename) {
if(*filename == '#' && ISDIGIT(filename[1])) {
char *ptr = filename;
unsigned long num = strtoul(&filename[1], &filename, 10);
URLPattern *pat = NULL;
if(num < glob->size) {
unsigned long i;
num--; /* make it zero based */
/* find the correct glob entry */
for(i = 0; i<glob->size; i++) {
if(glob->pattern[i].globindex == (int)num) {
pat = &glob->pattern[i];
break;
}
}
}
if(pat) {
switch(pat->type) {
case UPTSet:
if(pat->content.Set.elements) {
appendthis = pat->content.Set.elements[pat->content.Set.ptr_s];
appendlen =
strlen(pat->content.Set.elements[pat->content.Set.ptr_s]);
}
break;
case UPTCharRange:
numbuf[0] = pat->content.CharRange.ptr_c;
numbuf[1] = 0;
appendthis = numbuf;
appendlen = 1;
break;
case UPTNumRange:
msnprintf(numbuf, sizeof(numbuf), "%0*lu",
pat->content.NumRange.padlength,
pat->content.NumRange.ptr_n);
appendthis = numbuf;
appendlen = strlen(numbuf);
break;
default:
fprintf(stderr, "internal error: invalid pattern type (%d)\n",
(int)pat->type);
Curl_safefree(target);
return CURLE_FAILED_INIT;
}
}
else {
/* #[num] out of range, use the #[num] in the output */
filename = ptr;
appendthis = filename++;
appendlen = 1;
}
}
else {
appendthis = filename++;
appendlen = 1;
}
if(appendlen + stringlen >= allocsize) {
char *newstr;
/* we append a single byte to allow for the trailing byte to be appended
at the end of this function outside the while() loop */
allocsize = (appendlen + stringlen) * 2;
newstr = realloc(target, allocsize + 1);
if(!newstr) {
Curl_safefree(target);
return CURLE_OUT_OF_MEMORY;
}
target = newstr;
}
memcpy(&target[stringlen], appendthis, appendlen);
stringlen += appendlen;
}
target[stringlen]= '\0';
#if defined(MSDOS) || defined(WIN32)
{
char *sanitized;
SANITIZEcode sc = sanitize_file_name(&sanitized, target,
(SANITIZE_ALLOW_PATH |
SANITIZE_ALLOW_RESERVED));
Curl_safefree(target);
if(sc)
return CURLE_URL_MALFORMAT;
target = sanitized;
}
#endif /* MSDOS || WIN32 */
*result = target;
return CURLE_OK;
}
| YifuLiu/AliOS-Things | components/curl/src/tool_urlglob.c | C | apache-2.0 | 20,200 |
#ifndef HEADER_CURL_TOOL_URLGLOB_H
#define HEADER_CURL_TOOL_URLGLOB_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
typedef enum {
UPTSet = 1,
UPTCharRange,
UPTNumRange
} URLPatternType;
typedef struct {
URLPatternType type;
int globindex; /* the number of this particular glob or -1 if not used
within {} or [] */
union {
struct {
char **elements;
int size;
int ptr_s;
} Set;
struct {
char min_c;
char max_c;
char ptr_c;
int step;
} CharRange;
struct {
unsigned long min_n;
unsigned long max_n;
int padlength;
unsigned long ptr_n;
unsigned long step;
} NumRange;
} content;
} URLPattern;
/* the total number of globs supported */
#define GLOB_PATTERN_NUM 100
typedef struct {
URLPattern pattern[GLOB_PATTERN_NUM];
size_t size;
size_t urllen;
char *glob_buffer;
char beenhere;
const char *error; /* error message */
size_t pos; /* column position of error or 0 */
} URLGlob;
CURLcode glob_url(URLGlob**, char *, unsigned long *, FILE *);
CURLcode glob_next_url(char **, URLGlob *);
CURLcode glob_match_url(char **, char *, URLGlob *);
void glob_cleanup(URLGlob* glob);
#endif /* HEADER_CURL_TOOL_URLGLOB_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_urlglob.h | C | apache-2.0 | 2,270 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#include "tool_util.h"
#include "memdebug.h" /* keep this as LAST include */
#if defined(WIN32) && !defined(MSDOS)
struct timeval tvnow(void)
{
/*
** GetTickCount() is available on _all_ Windows versions from W95 up
** to nowadays. Returns milliseconds elapsed since last system boot,
** increases monotonically and wraps once 49.7 days have elapsed.
**
** GetTickCount64() is available on Windows version from Windows Vista
** and Windows Server 2008 up to nowadays. The resolution of the
** function is limited to the resolution of the system timer, which
** is typically in the range of 10 milliseconds to 16 milliseconds.
*/
struct timeval now;
#if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0600) && \
(!defined(__MINGW32__) || defined(__MINGW64_VERSION_MAJOR))
ULONGLONG milliseconds = GetTickCount64();
#else
DWORD milliseconds = GetTickCount();
#endif
now.tv_sec = (long)(milliseconds / 1000);
now.tv_usec = (long)((milliseconds % 1000) * 1000);
return now;
}
#elif defined(HAVE_CLOCK_GETTIME_MONOTONIC)
struct timeval tvnow(void)
{
/*
** clock_gettime() is granted to be increased monotonically when the
** monotonic clock is queried. Time starting point is unspecified, it
** could be the system start-up time, the Epoch, or something else,
** in any case the time starting point does not change once that the
** system has started up.
*/
struct timeval now;
struct timespec tsnow;
if(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow)) {
now.tv_sec = tsnow.tv_sec;
now.tv_usec = tsnow.tv_nsec / 1000;
}
/*
** Even when the configure process has truly detected monotonic clock
** availability, it might happen that it is not actually available at
** run-time. When this occurs simply fallback to other time source.
*/
#ifdef HAVE_GETTIMEOFDAY
else
(void)gettimeofday(&now, NULL);
#else
else {
now.tv_sec = (long)time(NULL);
now.tv_usec = 0;
}
#endif
return now;
}
#elif defined(HAVE_GETTIMEOFDAY)
struct timeval tvnow(void)
{
/*
** gettimeofday() is not granted to be increased monotonically, due to
** clock drifting and external source time synchronization it can jump
** forward or backward in time.
*/
struct timeval now;
(void)gettimeofday(&now, NULL);
return now;
}
#else
struct timeval tvnow(void)
{
/*
** time() returns the value of time in seconds since the Epoch.
*/
struct timeval now;
now.tv_sec = (long)time(NULL);
now.tv_usec = 0;
return now;
}
#endif
/*
* Make sure that the first argument is the more recent time, as otherwise
* we'll get a weird negative time-diff back...
*
* Returns: the time difference in number of milliseconds.
*/
long tvdiff(struct timeval newer, struct timeval older)
{
return (long)(newer.tv_sec-older.tv_sec)*1000+
(long)(newer.tv_usec-older.tv_usec)/1000;
}
| YifuLiu/AliOS-Things | components/curl/src/tool_util.c | C | apache-2.0 | 3,905 |
#ifndef HEADER_CURL_TOOL_UTIL_H
#define HEADER_CURL_TOOL_UTIL_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
struct timeval tvnow(void);
/*
* Make sure that the first argument (t1) is the more recent time and t2 is
* the older time, as otherwise you get a weird negative time-diff back...
*
* Returns: the time difference in number of milliseconds.
*/
long tvdiff(struct timeval t1, struct timeval t2);
#endif /* HEADER_CURL_TOOL_UTIL_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_util.h | C | apache-2.0 | 1,453 |
#ifndef HEADER_CURL_TOOL_VERSION_H
#define HEADER_CURL_TOOL_VERSION_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include <curl/curlver.h>
#define CURL_NAME "curl"
#define CURL_COPYRIGHT LIBCURL_COPYRIGHT
#define CURL_VERSION LIBCURL_VERSION
#define CURL_VERSION_MAJOR LIBCURL_VERSION_MAJOR
#define CURL_VERSION_MINOR LIBCURL_VERSION_MINOR
#define CURL_VERSION_PATCH LIBCURL_VERSION_PATCH
#define CURL_ID CURL_NAME " " CURL_VERSION " (" OS ") "
#endif /* HEADER_CURL_TOOL_VERSION_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_version.h | C | apache-2.0 | 1,470 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#ifdef __VMS
#if defined(__DECC) && !defined(__VAX) && \
defined(__CRTL_VER) && (__CRTL_VER >= 70301000)
#include <unixlib.h>
#endif
#define ENABLE_CURLX_PRINTF
#include "curlx.h"
#include "curlmsg_vms.h"
#include "tool_vms.h"
#include "memdebug.h" /* keep this as LAST include */
void decc$__posix_exit(int __status);
void decc$exit(int __status);
static int vms_shell = -1;
/* VMS has a DCL shell and and also has Unix shells ported to it.
* When curl is running under a Unix shell, we want it to be as much
* like Unix as possible.
*/
int is_vms_shell(void)
{
char *shell;
/* Have we checked the shell yet? */
if(vms_shell >= 0)
return vms_shell;
shell = getenv("SHELL");
/* No shell, means DCL */
if(shell == NULL) {
vms_shell = 1;
return 1;
}
/* Have to make sure some one did not set shell to DCL */
if(strcmp(shell, "DCL") == 0) {
vms_shell = 1;
return 1;
}
vms_shell = 0;
return 0;
}
/*
* VMS has two exit() routines. When running under a Unix style shell, then
* Unix style and the __posix_exit() routine is used.
*
* When running under the DCL shell, then the VMS encoded codes and decc$exit()
* is used.
*
* We can not use exit() or return a code from main() because the actual
* routine called depends on both the compiler version, compile options, and
* feature macro settings, and one of the exit routines is hidden at compile
* time.
*
* Since we want Curl to work properly under the VMS DCL shell and Unix
* shells under VMS, this routine should compile correctly regardless of
* the settings.
*/
void vms_special_exit(int code, int vms_show)
{
int vms_code;
/* The Posix exit mode is only available after VMS 7.0 */
#if __CRTL_VER >= 70000000
if(is_vms_shell() == 0) {
decc$__posix_exit(code);
}
#endif
if(code > CURL_LAST) { /* If CURL_LAST exceeded then */
vms_code = CURL_LAST; /* curlmsg.h is out of sync. */
}
else {
vms_code = vms_cond[code] | vms_show;
}
decc$exit(vms_code);
}
#if defined(__DECC) && !defined(__VAX) && \
defined(__CRTL_VER) && (__CRTL_VER >= 70301000)
/*
* 2004-09-19 SMS.
*
* decc_init()
*
* On non-VAX systems, use LIB$INITIALIZE to set a collection of C
* RTL features without using the DECC$* logical name method, nor
* requiring the user to define the corresponding logical names.
*/
/* Structure to hold a DECC$* feature name and its desired value. */
typedef struct {
char *name;
int value;
} decc_feat_t;
/* Array of DECC$* feature names and their desired values. */
static decc_feat_t decc_feat_array[] = {
/* Preserve command-line case with SET PROCESS/PARSE_STYLE=EXTENDED */
{ "DECC$ARGV_PARSE_STYLE", 1 },
/* Preserve case for file names on ODS5 disks. */
{ "DECC$EFS_CASE_PRESERVE", 1 },
/* Enable multiple dots (and most characters) in ODS5 file names,
while preserving VMS-ness of ";version". */
{ "DECC$EFS_CHARSET", 1 },
/* List terminator. */
{ (char *)NULL, 0 }
};
/* Flag to sense if decc_init() was called. */
static int decc_init_done = -1;
/* LIB$INITIALIZE initialization function. */
static void decc_init(void)
{
int feat_index;
int feat_value;
int feat_value_max;
int feat_value_min;
int i;
int sts;
/* Set the global flag to indicate that LIB$INITIALIZE worked. */
decc_init_done = 1;
/* Loop through all items in the decc_feat_array[]. */
for(i = 0; decc_feat_array[i].name != NULL; i++) {
/* Get the feature index. */
feat_index = decc$feature_get_index(decc_feat_array[i].name);
if(feat_index >= 0) {
/* Valid item. Collect its properties. */
feat_value = decc$feature_get_value(feat_index, 1);
feat_value_min = decc$feature_get_value(feat_index, 2);
feat_value_max = decc$feature_get_value(feat_index, 3);
if((decc_feat_array[i].value >= feat_value_min) &&
(decc_feat_array[i].value <= feat_value_max)) {
/* Valid value. Set it if necessary. */
if(feat_value != decc_feat_array[i].value) {
sts = decc$feature_set_value(feat_index, 1,
decc_feat_array[i].value);
}
}
else {
/* Invalid DECC feature value. */
printf(" INVALID DECC FEATURE VALUE, %d: %d <= %s <= %d.\n",
feat_value,
feat_value_min, decc_feat_array[i].name, feat_value_max);
}
}
else {
/* Invalid DECC feature name. */
printf(" UNKNOWN DECC FEATURE: %s.\n", decc_feat_array[i].name);
}
}
}
/* Get "decc_init()" into a valid, loaded LIB$INITIALIZE PSECT. */
#pragma nostandard
/* Establish the LIB$INITIALIZE PSECTs, with proper alignment and
other attributes. Note that "nopic" is significant only on VAX. */
#pragma extern_model save
#pragma extern_model strict_refdef "LIB$INITIALIZ" 2, nopic, nowrt
const int spare[8] = {0};
#pragma extern_model strict_refdef "LIB$INITIALIZE" 2, nopic, nowrt
void (*const x_decc_init)() = decc_init;
#pragma extern_model restore
/* Fake reference to ensure loading the LIB$INITIALIZE PSECT. */
#pragma extern_model save
int LIB$INITIALIZE(void);
#pragma extern_model strict_refdef
int dmy_lib$initialize = (int) LIB$INITIALIZE;
#pragma extern_model restore
#pragma standard
#endif /* __DECC && !__VAX && __CRTL_VER && __CRTL_VER >= 70301000 */
#endif /* __VMS */
| YifuLiu/AliOS-Things | components/curl/src/tool_vms.c | C | apache-2.0 | 6,401 |
#ifndef HEADER_CURL_TOOL_VMS_H
#define HEADER_CURL_TOOL_VMS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#ifdef __VMS
/*
* Forward-declaration of global variable vms_show defined
* in tool_main.c, used in main() as parameter for function
* vms_special_exit() to allow proper curl tool exiting.
*/
extern int vms_show;
int is_vms_shell(void);
void vms_special_exit(int code, int vms_show);
#undef exit
#define exit(__code) vms_special_exit((__code), (0))
#define VMS_STS(c,f,e,s) (((c&0xF)<<28)|((f&0xFFF)<<16)|((e&0x1FFF)<3)|(s&7))
#define VMSSTS_HIDE VMS_STS(1,0,0,0)
#endif /* __VMS */
#endif /* HEADER_CURL_TOOL_VMS_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_vms.h | C | apache-2.0 | 1,645 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_cfgable.h"
#include "tool_writeout.h"
#include "memdebug.h" /* keep this as LAST include */
typedef enum {
VAR_NONE, /* must be the first */
VAR_TOTAL_TIME,
VAR_NAMELOOKUP_TIME,
VAR_CONNECT_TIME,
VAR_APPCONNECT_TIME,
VAR_PRETRANSFER_TIME,
VAR_STARTTRANSFER_TIME,
VAR_SIZE_DOWNLOAD,
VAR_SIZE_UPLOAD,
VAR_SPEED_DOWNLOAD,
VAR_SPEED_UPLOAD,
VAR_HTTP_CODE,
VAR_HTTP_CODE_PROXY,
VAR_HEADER_SIZE,
VAR_REQUEST_SIZE,
VAR_EFFECTIVE_URL,
VAR_CONTENT_TYPE,
VAR_NUM_CONNECTS,
VAR_REDIRECT_TIME,
VAR_REDIRECT_COUNT,
VAR_FTP_ENTRY_PATH,
VAR_REDIRECT_URL,
VAR_SSL_VERIFY_RESULT,
VAR_PROXY_SSL_VERIFY_RESULT,
VAR_EFFECTIVE_FILENAME,
VAR_PRIMARY_IP,
VAR_PRIMARY_PORT,
VAR_LOCAL_IP,
VAR_LOCAL_PORT,
VAR_HTTP_VERSION,
VAR_SCHEME,
VAR_STDOUT,
VAR_STDERR,
VAR_NUM_OF_VARS /* must be the last */
} replaceid;
struct variable {
const char *name;
replaceid id;
};
static const struct variable replacements[]={
{"url_effective", VAR_EFFECTIVE_URL},
{"http_code", VAR_HTTP_CODE},
{"response_code", VAR_HTTP_CODE},
{"http_connect", VAR_HTTP_CODE_PROXY},
{"time_total", VAR_TOTAL_TIME},
{"time_namelookup", VAR_NAMELOOKUP_TIME},
{"time_connect", VAR_CONNECT_TIME},
{"time_appconnect", VAR_APPCONNECT_TIME},
{"time_pretransfer", VAR_PRETRANSFER_TIME},
{"time_starttransfer", VAR_STARTTRANSFER_TIME},
{"size_header", VAR_HEADER_SIZE},
{"size_request", VAR_REQUEST_SIZE},
{"size_download", VAR_SIZE_DOWNLOAD},
{"size_upload", VAR_SIZE_UPLOAD},
{"speed_download", VAR_SPEED_DOWNLOAD},
{"speed_upload", VAR_SPEED_UPLOAD},
{"content_type", VAR_CONTENT_TYPE},
{"num_connects", VAR_NUM_CONNECTS},
{"time_redirect", VAR_REDIRECT_TIME},
{"num_redirects", VAR_REDIRECT_COUNT},
{"ftp_entry_path", VAR_FTP_ENTRY_PATH},
{"redirect_url", VAR_REDIRECT_URL},
{"ssl_verify_result", VAR_SSL_VERIFY_RESULT},
{"proxy_ssl_verify_result", VAR_PROXY_SSL_VERIFY_RESULT},
{"filename_effective", VAR_EFFECTIVE_FILENAME},
{"remote_ip", VAR_PRIMARY_IP},
{"remote_port", VAR_PRIMARY_PORT},
{"local_ip", VAR_LOCAL_IP},
{"local_port", VAR_LOCAL_PORT},
{"http_version", VAR_HTTP_VERSION},
{"scheme", VAR_SCHEME},
{"stdout", VAR_STDOUT},
{"stderr", VAR_STDERR},
{NULL, VAR_NONE}
};
void ourWriteOut(CURL *curl, struct OutStruct *outs, const char *writeinfo)
{
FILE *stream = stdout;
const char *ptr = writeinfo;
char *stringp = NULL;
long longinfo;
double doubleinfo;
while(ptr && *ptr) {
if('%' == *ptr && ptr[1]) {
if('%' == ptr[1]) {
/* an escaped %-letter */
fputc('%', stream);
ptr += 2;
}
else {
/* this is meant as a variable to output */
char *end;
if('{' == ptr[1]) {
char keepit;
int i;
bool match = FALSE;
end = strchr(ptr, '}');
ptr += 2; /* pass the % and the { */
if(!end) {
fputs("%{", stream);
continue;
}
keepit = *end;
*end = 0; /* zero terminate */
for(i = 0; replacements[i].name; i++) {
if(curl_strequal(ptr, replacements[i].name)) {
match = TRUE;
switch(replacements[i].id) {
case VAR_EFFECTIVE_URL:
if((CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &stringp))
&& stringp)
fputs(stringp, stream);
break;
case VAR_HTTP_CODE:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &longinfo))
fprintf(stream, "%03ld", longinfo);
break;
case VAR_HTTP_CODE_PROXY:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_HTTP_CONNECTCODE,
&longinfo))
fprintf(stream, "%03ld", longinfo);
break;
case VAR_HEADER_SIZE:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_HEADER_SIZE, &longinfo))
fprintf(stream, "%ld", longinfo);
break;
case VAR_REQUEST_SIZE:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_REQUEST_SIZE, &longinfo))
fprintf(stream, "%ld", longinfo);
break;
case VAR_NUM_CONNECTS:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_NUM_CONNECTS, &longinfo))
fprintf(stream, "%ld", longinfo);
break;
case VAR_REDIRECT_COUNT:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_REDIRECT_COUNT, &longinfo))
fprintf(stream, "%ld", longinfo);
break;
case VAR_REDIRECT_TIME:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_REDIRECT_TIME,
&doubleinfo))
fprintf(stream, "%.6f", doubleinfo);
break;
case VAR_TOTAL_TIME:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &doubleinfo))
fprintf(stream, "%.6f", doubleinfo);
break;
case VAR_NAMELOOKUP_TIME:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME,
&doubleinfo))
fprintf(stream, "%.6f", doubleinfo);
break;
case VAR_CONNECT_TIME:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &doubleinfo))
fprintf(stream, "%.6f", doubleinfo);
break;
case VAR_APPCONNECT_TIME:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME,
&doubleinfo))
fprintf(stream, "%.6f", doubleinfo);
break;
case VAR_PRETRANSFER_TIME:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME,
&doubleinfo))
fprintf(stream, "%.6f", doubleinfo);
break;
case VAR_STARTTRANSFER_TIME:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME,
&doubleinfo))
fprintf(stream, "%.6f", doubleinfo);
break;
case VAR_SIZE_UPLOAD:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &doubleinfo))
fprintf(stream, "%.0f", doubleinfo);
break;
case VAR_SIZE_DOWNLOAD:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD,
&doubleinfo))
fprintf(stream, "%.0f", doubleinfo);
break;
case VAR_SPEED_DOWNLOAD:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD,
&doubleinfo))
fprintf(stream, "%.3f", doubleinfo);
break;
case VAR_SPEED_UPLOAD:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD, &doubleinfo))
fprintf(stream, "%.3f", doubleinfo);
break;
case VAR_CONTENT_TYPE:
if((CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &stringp))
&& stringp)
fputs(stringp, stream);
break;
case VAR_FTP_ENTRY_PATH:
if((CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_FTP_ENTRY_PATH, &stringp))
&& stringp)
fputs(stringp, stream);
break;
case VAR_REDIRECT_URL:
if((CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &stringp))
&& stringp)
fputs(stringp, stream);
break;
case VAR_SSL_VERIFY_RESULT:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_SSL_VERIFYRESULT,
&longinfo))
fprintf(stream, "%ld", longinfo);
break;
case VAR_PROXY_SSL_VERIFY_RESULT:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_PROXY_SSL_VERIFYRESULT,
&longinfo))
fprintf(stream, "%ld", longinfo);
break;
case VAR_EFFECTIVE_FILENAME:
if(outs->filename)
fprintf(stream, "%s", outs->filename);
break;
case VAR_PRIMARY_IP:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_PRIMARY_IP,
&stringp))
fprintf(stream, "%s", stringp);
break;
case VAR_PRIMARY_PORT:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_PRIMARY_PORT,
&longinfo))
fprintf(stream, "%ld", longinfo);
break;
case VAR_LOCAL_IP:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_LOCAL_IP,
&stringp))
fprintf(stream, "%s", stringp);
break;
case VAR_LOCAL_PORT:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_LOCAL_PORT,
&longinfo))
fprintf(stream, "%ld", longinfo);
break;
case VAR_HTTP_VERSION:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_HTTP_VERSION,
&longinfo)) {
const char *version = "0";
switch(longinfo) {
case CURL_HTTP_VERSION_1_0:
version = "1.0";
break;
case CURL_HTTP_VERSION_1_1:
version = "1.1";
break;
case CURL_HTTP_VERSION_2_0:
version = "2";
break;
}
fprintf(stream, version);
}
break;
case VAR_SCHEME:
if(CURLE_OK ==
curl_easy_getinfo(curl, CURLINFO_SCHEME,
&stringp))
fprintf(stream, "%s", stringp);
break;
case VAR_STDOUT:
stream = stdout;
break;
case VAR_STDERR:
stream = stderr;
break;
default:
break;
}
break;
}
}
if(!match) {
fprintf(stderr, "curl: unknown --write-out variable: '%s'\n", ptr);
}
ptr = end + 1; /* pass the end */
*end = keepit;
}
else {
/* illegal syntax, then just output the characters that are used */
fputc('%', stream);
fputc(ptr[1], stream);
ptr += 2;
}
}
}
else if('\\' == *ptr && ptr[1]) {
switch(ptr[1]) {
case 'r':
fputc('\r', stream);
break;
case 'n':
fputc('\n', stream);
break;
case 't':
fputc('\t', stream);
break;
default:
/* unknown, just output this */
fputc(*ptr, stream);
fputc(ptr[1], stream);
break;
}
ptr += 2;
}
else {
fputc(*ptr, stream);
ptr++;
}
}
}
| YifuLiu/AliOS-Things | components/curl/src/tool_writeout.c | C | apache-2.0 | 13,314 |
#ifndef HEADER_CURL_TOOL_WRITEOUT_H
#define HEADER_CURL_TOOL_WRITEOUT_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
void ourWriteOut(CURL *curl, struct OutStruct *outs, const char *writeinfo);
#endif /* HEADER_CURL_TOOL_WRITEOUT_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_writeout.h | C | apache-2.0 | 1,242 |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#ifdef HAVE_FSETXATTR
# include <sys/xattr.h> /* header from libc, not from libattr */
# define USE_XATTR
#elif defined(__FreeBSD_version) && (__FreeBSD_version > 500000)
# include <sys/types.h>
# include <sys/extattr.h>
# define USE_XATTR
#endif
#include "tool_xattr.h"
#include "memdebug.h" /* keep this as LAST include */
#ifdef USE_XATTR
/* mapping table of curl metadata to extended attribute names */
static const struct xattr_mapping {
const char *attr; /* name of the xattr */
CURLINFO info;
} mappings[] = {
/* mappings proposed by
* https://freedesktop.org/wiki/CommonExtendedAttributes/
*/
{ "user.xdg.origin.url", CURLINFO_EFFECTIVE_URL },
{ "user.mime_type", CURLINFO_CONTENT_TYPE },
{ NULL, CURLINFO_NONE } /* last element, abort loop here */
};
/* returns TRUE if a new URL is returned, that then needs to be freed */
/* @unittest: 1621 */
#ifdef UNITTESTS
bool stripcredentials(char **url);
#else
static
#endif
bool stripcredentials(char **url)
{
CURLU *u;
CURLUcode uc;
char *nurl;
u = curl_url();
if(u) {
uc = curl_url_set(u, CURLUPART_URL, *url, 0);
if(uc)
goto error;
uc = curl_url_set(u, CURLUPART_USER, NULL, 0);
if(uc)
goto error;
uc = curl_url_set(u, CURLUPART_PASSWORD, NULL, 0);
if(uc)
goto error;
uc = curl_url_get(u, CURLUPART_URL, &nurl, 0);
if(uc)
goto error;
curl_url_cleanup(u);
*url = nurl;
return TRUE;
}
error:
curl_url_cleanup(u);
return FALSE;
}
/* store metadata from the curl request alongside the downloaded
* file using extended attributes
*/
int fwrite_xattr(CURL *curl, int fd)
{
int i = 0;
int err = 0;
/* loop through all xattr-curlinfo pairs and abort on a set error */
while(err == 0 && mappings[i].attr != NULL) {
char *value = NULL;
CURLcode result = curl_easy_getinfo(curl, mappings[i].info, &value);
if(!result && value) {
bool freeptr = FALSE;
if(CURLINFO_EFFECTIVE_URL == mappings[i].info)
freeptr = stripcredentials(&value);
if(value) {
#ifdef HAVE_FSETXATTR_6
err = fsetxattr(fd, mappings[i].attr, value, strlen(value), 0, 0);
#elif defined(HAVE_FSETXATTR_5)
err = fsetxattr(fd, mappings[i].attr, value, strlen(value), 0);
#elif defined(__FreeBSD_version)
{
ssize_t rc = extattr_set_fd(fd, EXTATTR_NAMESPACE_USER,
mappings[i].attr, value, strlen(value));
/* FreeBSD's extattr_set_fd returns the length of the extended
attribute */
err = (rc < 0 ? -1 : 0);
}
#endif
if(freeptr)
curl_free(value);
}
}
i++;
}
return err;
}
#else
int fwrite_xattr(CURL *curl, int fd)
{
(void)curl;
(void)fd;
return 0;
}
#endif
| YifuLiu/AliOS-Things | components/curl/src/tool_xattr.c | C | apache-2.0 | 3,860 |
#ifndef HEADER_CURL_TOOL_XATTR_H
#define HEADER_CURL_TOOL_XATTR_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
int fwrite_xattr(CURL *curl, int fd);
#endif /* HEADER_CURL_TOOL_XATTR_H */
| YifuLiu/AliOS-Things | components/curl/src/tool_xattr.h | C | apache-2.0 | 1,194 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#if AOS_COMP_CLI
#include "aos/debug.h"
#include "aos/cli.h"
static void debug_help_show(void)
{
aos_cli_printf("You can use debug cmd to show api test:\r\n");
aos_cli_printf("debug_api help --- show this\r\n");
aos_cli_printf("debug_api 1 --- show memory info\r\n");
aos_cli_printf("debug_api 2 --- show task info\r\n");
aos_cli_printf("debug_api 3 --- show bufqueue info\r\n");
aos_cli_printf("debug_api 4 --- show queue info\r\n");
aos_cli_printf("debug_api 5 --- show sem info\r\n");
aos_cli_printf("debug_api 6 --- show mutex info\r\n");
aos_cli_printf("debug_api 7 --- show backtrace now\r\n");
aos_cli_printf("debug_api 8 --- show backtrace task\r\n");
aos_cli_printf("debug_api all --- show all above\r\n");
}
static void debug_api_example(int argc, char **argv)
{
if (argc != 2) {
aos_cli_printf("use 'debug_api help' for test\r\n");
return;
}
if (strcmp(argv[1], "help") == 0) {
debug_help_show();
} else if (strcmp(argv[1], "1") == 0) {
aos_debug_mm_overview(aos_cli_printf);
} else if (strcmp(argv[1], "2") == 0) {
aos_debug_task_overview(aos_cli_printf);
} else if (strcmp(argv[1], "3") == 0) {
aos_debug_buf_queue_overview(aos_cli_printf);
} else if (strcmp(argv[1], "4") == 0) {
aos_debug_queue_overview(aos_cli_printf);
} else if (strcmp(argv[1], "5") == 0) {
aos_debug_sem_overview(aos_cli_printf);
} else if (strcmp(argv[1], "6") == 0) {
aos_debug_mutex_overview(aos_cli_printf);
} else if (strcmp(argv[1], "7") == 0) {
aos_debug_backtrace_now(aos_cli_printf);
} else if (strcmp(argv[1], "8") == 0) {
aos_debug_backtrace_task("idle_task", aos_cli_printf);
} else if (strcmp(argv[1], "all") == 0) {
aos_debug_overview(aos_cli_printf);
} else {
aos_cli_printf("debug example cmd not exist\r\n");
}
}
/* reg args: fun, cmd, description*/
ALIOS_CLI_CMD_REGISTER(debug_api_example, debug_api, debug api example)
#endif /* AOS_COMP_CLI */
| YifuLiu/AliOS-Things | components/debug/example/debug_example.c | C | apache-2.0 | 2,009 |
/**
* @file debug.h
* @copyright Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef AOS_DBG_H
#define AOS_DBG_H
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup debug_aos_api debug
* @{
*/
#include <stdint.h>
#include <k_api.h>
/**
* Show current contex backtrace
*
* @param[in] print_func function to output information, NULL for "printf"
*
* @retrun NULL
*/
void aos_debug_backtrace_now(int32_t (*print_func)(const char *fmt, ...));
/**
* Show task backtrace
*
* @param[in] taskname the task name which is need to be got
* @param[in] print_func function to output information, NULL for "printf"
*
* @retrun NULL
*/
void aos_debug_backtrace_task(char *taskname, int32_t (*print_func)(const char *fmt, ...));
/**
* Show the overview of memory(heap and pool)
*
* @param[in] print_func function to output information, NULL for "printf"
*
* @retrun NULL
*/
void aos_debug_mm_overview(int32_t (*print_func)(const char *fmt, ...));
/**
* Show the overview of tasks
*
* @param[in] print_func function to output information, NULL for "printf"
*
* @retrun NULL
*/
void aos_debug_task_overview(int32_t (*print_func)(const char *fmt, ...));
/**
* Show the overview of buf_queue
*
* @param[in] print_func function to output information, NULL for "printf"
*
* @retrun NULL
*/
void aos_debug_buf_queue_overview(int32_t (*print_func)(const char *fmt, ...));
/**
* Show the overview of queue
*
* @param[in] print_func function to output information, NULL for "printf"
*
* @retrun NULL
*/
void aos_debug_queue_overview(int32_t (*print_func)(const char *fmt, ...));
/**
* Show the overview of sem
*
* @param[in] print_func function to output information, NULL for "printf"
*
* @retrun NULL
*/
void aos_debug_sem_overview(int32_t (*print_func)(const char *fmt, ...));
/**
* Show the overview of mutex
*
* @param[in] print_func function to output information, NULL for "printf"
*
* @retrun NULL
*/
void aos_debug_mutex_overview(int32_t (*print_func)(const char *fmt, ...));
/**
* Show the overview of all(task/memory/bufqueue/queue/sem)
*
* @param[in] print_func function to output information, NULL for "printf"
*
* @retrun NULL
*/
void aos_debug_overview(int32_t (*print_func)(const char *fmt, ...));
/**
* This function will statistics the task run time in the previous statistics cycle
*
* @return NULL
*/
void aos_debug_task_cpu_usage_stats(void);
/**
* This function will get the cpuusage for the specified task
*
* @param[in] taskname the task name which is need to be got
*
* @return -1 is error, others is cpuusage, the units are 1/10,000
*/
int32_t aos_debug_task_cpu_usage_get(char *taskname);
/**
* This function will get the cpuusage for the specified CPU
*
* @param[in] cpuid the cpu id to obtain CPU utilization
*
* @return cpuusage, the units are 1/10,000
*/
uint32_t aos_debug_total_cpu_usage_get(uint32_t cpuid);
/**
* This function will show the statistics for CPU utilization
*
* @return NULL
*/
void aos_debug_total_cpu_usage_show(void);
/**
* system assert, called by k_err_proc
*
* @param[in] err the kernel err status
* @param[in] file same as __FILE__
* @param[in] file same as __line__
* @return NULL
*/
void aos_debug_fatal_error(kstat_t err, char *file, int32_t line);
/**
* This function support debug print same as printf
*
* @return 0 is ok, others err
*/
int32_t aos_debug_printf(const char *fmt, ...);
#define printk aos_debug_printf
/**
* This function init debug module
*
* @return NULL
*/
void aos_debug_init(void);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* AOS_DBG_H */
| YifuLiu/AliOS-Things | components/debug/include/aos/debug.h | C | apache-2.0 | 3,666 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include "debug_api.h"
typedef int32_t (*BT_PRINT)(const char *fmt, ...);
void aos_debug_backtrace_now(int32_t (*print_func)(const char *fmt, ...))
{
BT_PRINT bt_printf = print_func ? print_func : printf;
debug_backtrace_now(bt_printf);
}
void aos_debug_backtrace_task(char *taskname, int32_t (*print_func)(const char *fmt, ...))
{
BT_PRINT bt_printf = print_func ? print_func : printf;
debug_backtrace_task(taskname, bt_printf);
}
void aos_debug_mm_overview(int32_t (*print_func)(const char *fmt, ...))
{
BT_PRINT bt_printf = print_func ? print_func : printf;
debug_mm_overview(bt_printf);
}
void aos_debug_task_overview(int32_t (*print_func)(const char *fmt, ...))
{
BT_PRINT bt_printf = print_func ? print_func : printf;
debug_task_overview(bt_printf);
}
void aos_debug_buf_queue_overview(int32_t (*print_func)(const char *fmt, ...))
{
BT_PRINT bt_printf = print_func ? print_func : printf;
debug_buf_queue_overview(bt_printf);
}
void aos_debug_queue_overview(int32_t (*print_func)(const char *fmt, ...))
{
BT_PRINT bt_printf = print_func ? print_func : printf;
debug_queue_overview(bt_printf);
}
void aos_debug_sem_overview(int32_t (*print_func)(const char *fmt, ...))
{
BT_PRINT bt_printf = print_func ? print_func : printf;
debug_sem_overview(bt_printf);
}
void aos_debug_mutex_overview(int32_t (*print_func)(const char *fmt, ...))
{
BT_PRINT bt_printf = print_func ? print_func : printf;
debug_mutex_overview(bt_printf);
}
void aos_debug_overview(int32_t (*print_func)(const char *fmt, ...))
{
BT_PRINT bt_printf = print_func ? print_func : printf;
debug_overview(bt_printf);
}
#if (RHINO_CONFIG_SYS_STATS > 0)
void aos_debug_task_cpu_usage_stats(void)
{
debug_task_cpu_usage_stats();
}
int32_t aos_debug_task_cpu_usage_get(char *taskname)
{
ktask_t *task;
task = krhino_task_find(taskname);
if (task == NULL) {
return -1;
}
return debug_task_cpu_usage_get(task);
}
uint32_t aos_debug_total_cpu_usage_get(uint32_t cpuid)
{
return debug_total_cpu_usage_get(cpuid);
}
void aos_debug_total_cpu_usage_show(void)
{
debug_total_cpu_usage_show(NULL, 0, 0);
}
#endif
void aos_debug_fatal_error(kstat_t err, char *file, int32_t line)
{
debug_fatal_error(err, file, line);
}
void aos_debug_init(void)
{
debug_init();
} | YifuLiu/AliOS-Things | components/debug/src/debug.c | C | apache-2.0 | 2,435 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef DBG_API_H
#define DBG_API_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include "k_api.h"
#include "debug_infoget.h"
#include "debug_overview.h"
#include "debug_panic.h"
#include "debug_backtrace.h"
#include "debug_print.h"
#include "debug_test.h"
#include "debug_cli_cmd.h"
#include "debug_dumpsys.h"
#include "debug_cpuusage.h"
#if DEBUG_LAST_WORD_ENABLE
#include "debug_lastword.h"
#endif
/* system reboot reason description */
#define DEBUG_REBOOT_REASON_WD_RST 0x01 /**< Watchdog reset */
#define DEBUG_REBOOT_REASON_PANIC 0x02 /**< System panic */
#define DEBUG_REBOOT_REASON_REPOWER 0x03 /**< System repower */
#define DEBUG_REBOOT_REASON_FATAL_ERR 0x04 /**< System fatal error */
#define DEBUG_REBOOT_CMD_REASON 0x05 /**< Reboot cmd */
#define DEBUG_REBOOT_UNKNOWN_REASON 0x06 /**< unknown reason */
#ifdef __cplusplus
}
#endif
#endif /* DBG_API_H */
| YifuLiu/AliOS-Things | components/debug/src/debug_api.h | C | apache-2.0 | 971 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include "k_api.h"
/* follow functions should defined by arch\...\backtrace.c */
extern int backtrace_now(int (*print_func)(const char *fmt, ...));
extern int backtrace_task(void *task, int (*print_func)(const char *fmt, ...));
void debug_backtrace_now(int32_t (*print_func)(const char *fmt, ...))
{
backtrace_now(print_func);
}
void debug_backtrace_task(char *taskname, int32_t (*print_func)(const char *fmt, ...))
{
klist_t *listnode;
ktask_t *task;
for (listnode = g_kobj_list.task_head.next;
listnode != &g_kobj_list.task_head; listnode = listnode->next) {
task = krhino_list_entry(listnode, ktask_t, task_stats_item);
if (taskname) {
if (0 == strcmp(taskname, "all")) {
print_func("task name \"%s\" \r\n",
((ktask_t *)task)->task_name ? ((ktask_t *)task)->task_name : "anonym");
backtrace_task(task, print_func);
} else {
if (0 == strcmp(taskname, task->task_name)) {
backtrace_task(task, print_func);
}
}
}
}
}
void backtrace_handle(char *PC, int *SP, char *LR, int (*print_func)(const char *fmt, ...));
void debug_panic_backtrace(char *PC, int *SP, char *LR,
int (*print_func)(const char *fmt, ...))
{
backtrace_handle(PC, SP, LR, print_func);
}
| YifuLiu/AliOS-Things | components/debug/src/debug_backtrace.c | C | apache-2.0 | 1,469 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef DEBUG_BACKTRACE_H
#define DEBUG_BACKTRACE_H
#ifdef __cplusplus
extern "C"
{
#endif
void debug_backtrace_now(int32_t (*print_func)(const char *fmt, ...));
void debug_backtrace_task(char *taskname, int32_t (*print_func)(const char *fmt, ...));
#ifdef __cplusplus
}
#endif
#endif /* DEBUG_BACKTRACE_H */
| YifuLiu/AliOS-Things | components/debug/src/debug_backtrace.h | C | apache-2.0 | 379 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#if AOS_COMP_CLI
#include <stdlib.h>
#include <unistd.h>
#include "k_api.h"
#include "aos/cli.h"
#include "aos/kernel.h"
#include "debug_api.h"
#if (RHINO_CONFIG_UCLI)
#include "ucli.h"
#endif
#if defined (__CC_ARM) && defined(__MICROLIB)
#define TOSTR(s) #s
#else
#define TOSTR
#endif
static void version_cmd(char *buf, int32_t len, int32_t argc, char **argv);
static void uptime_cmd(char *buf, int32_t len, int32_t argc, char **argv);
static void debug_cmd(char *buf, int32_t len, int32_t argc, char **argv);
static void msleep_cmd(char *buf, int32_t len, int32_t argc, char **argv);
static void devname_cmd(char *buf, int32_t len, int32_t argc, char **argv);
static void pmem_cmd(char *buf, int32_t len, int32_t argc, char **argv);
static void mmem_cmd(char *buf, int32_t len, int32_t argc, char **argv);
static void func_cmd(char *buf, int32_t len, int32_t argc, char **argv);
static void debug_panic_runto_cli(char *buf, int32_t len, int32_t argc, char **argv);
static const struct cli_command built_ins[] = {
{ "debug", "show debug info", debug_cmd },
/*aos_rhino*/
{ "sysver", "system version", version_cmd },
{ "time", "system time", uptime_cmd },
{ "msleep", "sleep miliseconds", msleep_cmd },
{ "p", "print memory", pmem_cmd },
{ "m", "modify memory", mmem_cmd },
{ "f", "run a function", func_cmd },
{ "devname", "print device name", devname_cmd },
{ "err2cli", "set exec runto cli", debug_panic_runto_cli },
};
static void debug_cmd(char *buf, int32_t len, int32_t argc, char **argv)
{
debug_overview(aos_cli_printf);
}
static void version_cmd(char *buf, int32_t len, int32_t argc, char **argv)
{
#ifdef OSAL_RHINO
aos_cli_printf("kernel version :%d\r\n", (int32_t)krhino_version_get());
#else
aos_cli_printf("kernel version :posix\r\n");
#endif
}
static void uptime_cmd(char *buf, int32_t len, int32_t argc, char **argv)
{
aos_cli_printf("UP time %ld ms\r\n", (long)krhino_sys_time_get());
}
static void msleep_cmd(char *buf, int32_t len, int32_t argc, char **argv)
{
int seconds;
if (argc != 2) {
aos_cli_printf("Usage: msleep seconds\r\n");
return;
}
seconds = atoi(argv[1]);
if (seconds > 0) {
krhino_task_sleep(krhino_ms_to_ticks(seconds));
} else {
aos_cli_printf("invalid param %s\r\n", argv[1]);
}
}
static void devname_cmd(char *buf, int32_t len, int32_t argc, char **argv)
{
#ifdef SYSINFO_DEVICE_NAME
aos_cli_printf("device name: %s\r\n", TOSTR(SYSINFO_DEVICE_NAME));
#else
aos_cli_printf("device name: not defined on board\r\n");
#endif
}
uint32_t __attribute__((weak)) _system_ram_start = 0;
uint32_t __attribute__((weak)) _system_ram_len = 0;
static void pmem_cmd(char *buf, int32_t len, int32_t argc, char **argv)
{
int32_t i;
int32_t nunits = 16;
int32_t width = 4;
//char *addr = NULL;
uint32_t addr = 0;
switch (argc) {
case 4:
width = strtoul(argv[3], NULL, 0);
case 3:
nunits = strtoul(argv[2], NULL, 0);
nunits = nunits > 0x400 ? 0x400 : nunits;
case 2:
if (0 == strcmp(argv[1], "all")) {
aos_cli_printf("ram start: 0x%x len: 0x%x\n", _system_ram_start, _system_ram_len);
if ((_system_ram_start != 0) && (_system_ram_len != 0)) {
addr = _system_ram_start;
nunits = _system_ram_len / 4;
width = 4;
}
} else {
addr = strtoul(argv[1], NULL, 0);
}
break;
default:
aos_cli_printf("p <addr> <nunits> <width>\r\n"
"addr : address to display\r\n"
"nunits: number of units to display (default is 16)\r\n"
"width : width of unit, 1/2/4 (default is 4)\r\n");
return;
}
switch (width) {
case 1:
for (i = 0; i < nunits; i++) {
if (i % 16 == 0) {
aos_cli_printf("0x%08x:", addr);
}
aos_cli_printf(" %02x", *(unsigned char *)addr);
addr += 1;
if (i % 16 == 15) {
aos_cli_printf("\r\n");
}
}
break;
case 2:
for (i = 0; i < nunits; i++) {
if (i % 8 == 0) {
aos_cli_printf("0x%08x:", addr);
}
aos_cli_printf(" %04x", *(unsigned short *)addr);
addr += 2;
if (i % 8 == 7) {
aos_cli_printf("\r\n");
}
}
break;
default:
for (i = 0; i < nunits; i++) {
if (i % 4 == 0) {
aos_cli_printf("0x%08x:", addr);
}
aos_cli_printf(" %08x", *(unsigned int *)addr);
addr += 4;
if (i % 4 == 3) {
aos_cli_printf("\r\n");
}
}
break;
}
}
static void mmem_cmd(char *buf, int32_t len, int32_t argc, char **argv)
{
void *addr = NULL;
int32_t width = 4;
uint32_t value = 0;
uint32_t old_value;
uint32_t new_value;
switch (argc) {
case 4:
width = strtoul(argv[3], NULL, 0);
case 3:
value = strtoul(argv[2], NULL, 0);
case 2:
addr = (void *)strtoul(argv[1], NULL, 0);
break;
default:
aos_cli_printf("m <addr> <value> <width>\r\n"
"addr : address to modify\r\n"
"value : new value (default is 0)\r\n"
"width : width of unit, 1/2/4 (default is 4)\r\n");
return;
}
switch (width) {
case 1:
old_value = (uint32_t)(*(uint8_t volatile *)addr);
*(uint8_t volatile *)addr = (uint8_t)value;
new_value = (uint32_t)(*(uint8_t volatile *)addr);
break;
case 2:
old_value = (uint32_t)(*(unsigned short volatile *)addr);
*(unsigned short volatile *)addr = (unsigned short)value;
new_value = (uint32_t)(*(unsigned short volatile *)addr);
break;
case 4:
default:
old_value = *(uint32_t volatile *)addr;
*(uint32_t volatile *)addr = (uint32_t)value;
new_value = *(uint32_t volatile *)addr;
break;
}
aos_cli_printf("value on 0x%x change from 0x%x to 0x%x.\r\n", (uint32_t)addr,
old_value, new_value);
}
static void func_cmd(char *buf, int32_t len, int32_t argc, char **argv)
{
uint32_t idx, ret;
uint32_t para[8] = {0};
typedef uint32_t (*func_ptr_t)(uint32_t a1, uint32_t a2, uint32_t a3, uint32_t a4,
uint32_t a5, uint32_t a6, uint32_t a7, uint32_t a8);
func_ptr_t func_ptr;
if (argc == 1) {
aos_cli_printf("para error\r\n");
return;
}
argc = argc > 10 ? 10 : argc;
func_ptr = (func_ptr_t)strtoul(argv[1], NULL, 0);
for (idx = 2 ; idx < argc ; idx++) {
para[idx - 2] = strtoul(argv[idx], NULL, 0);
}
aos_cli_printf("function %p runing...\r\n", func_ptr);
#ifdef __thumb__
func_ptr = (func_ptr_t)((unsigned int)(func_ptr) + 1);
#endif
ret = func_ptr(para[0], para[1], para[2], para[3], para[4], para[5], para[6], para[7]);
aos_cli_printf("function %p return 0x%x.\r\n", func_ptr, ret);
}
static void debug_panic_runto_cli(char *buf, int32_t len, int32_t argc, char **argv)
{
if (argc == 2) {
int32_t flag = strtoul(argv[1], NULL, 0);
if (flag == 1) {
g_crash_not_reboot = OS_PANIC_NOT_REBOOT;
} else {
g_crash_not_reboot = 0;
}
aos_cli_printf("set panic_runto_cli flag:0x%x\r\n", g_crash_not_reboot);
}
}
static void debug_default_cmds_register(void)
{
int32_t ret;
ret = aos_cli_register_commands(built_ins, sizeof(built_ins) / sizeof(struct cli_command));
if (ret) {
printf("%s %d failed, ret = %d\r\n", __func__, __LINE__, ret);
}
}
void debug_cli_cmd_init(void)
{
debug_default_cmds_register();
debug_dumpsys_cmds_register();
#if (RHINO_CONFIG_SYS_STATS > 0)
debug_cpuusage_cmds_register();
#endif
}
#endif /* #if AOS_COMP_CLI */
| YifuLiu/AliOS-Things | components/debug/src/debug_cli_cmd.c | C | apache-2.0 | 8,489 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef DEBUG_CLI_CMD_H
#define DEBUG_CLI_CMD_H
#ifdef __cplusplus
extern "C"
{
#endif
void debug_cli_cmd_init(void);
#ifdef __cplusplus
}
#endif
#endif /* DEBUG_CLI_CMD_H */
| YifuLiu/AliOS-Things | components/debug/src/debug_cli_cmd.h | C | apache-2.0 | 244 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#if AOS_COMP_CLI
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "k_api.h"
#include "debug_api.h"
#include "aos/cli.h"
#if (RHINO_CONFIG_SYS_STATS > 0)
#define CPU_USAGE_DEFAULT_PRI 7
#define CPU_USAGE_STACK 4048
ktask_t *cpuusage_task;
int sync_mode = 0;
ksem_t sync_sem;
struct statistics_param {
uint32_t period;
uint32_t total;
uint32_t record_to_file;
};
typedef struct {
char task_name[32];
uint32_t task_cpu_usage;
} task_cpuusage_info;
static uint32_t task_cpu_usage_period = 0;
void debug_task_cpu_usage_stats(void)
{
uint32_t i;
klist_t *taskhead = &g_kobj_list.task_head;
klist_t *taskend = taskhead;
klist_t *tmp;
ktask_t *task;
lr_timer_t cur_time;
lr_timer_t exec_time;
static lr_timer_t stats_start = 0;
lr_timer_t stats_end;
(void)i; /* to avoid compiler warning */
CPSR_ALLOC();
RHINO_CRITICAL_ENTER();
#if (RHINO_CONFIG_CPU_NUM > 1)
for (i = 0; i < RHINO_CONFIG_CPU_NUM; i++) {
cur_time = (lr_timer_t)LR_COUNT_GET();
exec_time = cur_time - g_active_task[i]->task_time_start;
g_active_task[i]->task_time_total_run += (sys_time_t)exec_time;
g_active_task[i]->task_time_start = cur_time;
}
#else
cur_time = (lr_timer_t)LR_COUNT_GET();
exec_time = cur_time - g_active_task[0]->task_time_start;
g_active_task[0]->task_time_total_run += (sys_time_t)exec_time;
g_active_task[0]->task_time_start = cur_time;
#endif
for (tmp = taskhead->next; tmp != taskend; tmp = tmp->next) {
task = krhino_list_entry(tmp, ktask_t, task_stats_item);
task->task_exec_time = task->task_time_total_run -
task->task_time_total_run_prev;
task->task_time_total_run_prev = task->task_time_total_run;
}
RHINO_CRITICAL_EXIT();
stats_end = (lr_timer_t)LR_COUNT_GET();
task_cpu_usage_period = stats_end - stats_start;
stats_start = stats_end;
}
void debug_total_cpu_usage_show(struct cpuusage_data * cpuusage_record, int32_t record_len,int32_t index)
{
uint32_t i, j;
klist_t *taskhead = &g_kobj_list.task_head;
klist_t *taskend = taskhead;
klist_t *tmp;
ktask_t *task;
const char *task_name;
lr_timer_t task_cpu_usage;
uint32_t total_cpu_usage[RHINO_CONFIG_CPU_NUM];
uint32_t tasknum = 0;
task_cpuusage_info *taskinfo;
task_cpuusage_info *taskinfoeach;
if (cpuusage_record == NULL) {
aos_cli_printf("-----------------------\r\n");
}
#if (RHINO_CONFIG_CPU_NUM > 1)
for (i = 0; i < RHINO_CONFIG_CPU_NUM; i++) {
total_cpu_usage[i] = debug_total_cpu_usage_get(i);
if (cpuusage_record != NULL) {
if (cpuusage_record[i].taskname[0] == 0) {
snprintf((char *)cpuusage_record[i].taskname, CPU_USAGE_MAX_TASKNAME_LEN, "CPU%d", (int)i);
}
cpuusage_record[i].cpuusage[index] = (float)total_cpu_usage[i] / 100;
} else {
aos_cli_printf("CPU%d usage :%3d.%02d%% \r\n", (int)i, (int)total_cpu_usage[i] / 100,
(int)total_cpu_usage[i] % 100);
}
}
#else
total_cpu_usage[0] = debug_total_cpu_usage_get(0);
if (cpuusage_record != NULL) {
if (cpuusage_record[0].taskname[0] == 0) {
snprintf(cpuusage_record[0].taskname, CPU_USAGE_MAX_TASKNAME_LEN, "CPU");
}
cpuusage_record[0].cpuusage[index] = (float)total_cpu_usage[0] / 100;
} else {
aos_cli_printf("CPU usage :%3d.%02d%% \r\n", (int)total_cpu_usage[0] / 100,
(int)total_cpu_usage[0] % 100);
}
#endif
if (cpuusage_record == NULL) {
aos_cli_printf("---------------------------\r\n");
aos_cli_printf("Name %%CPU\r\n");
aos_cli_printf("---------------------------\r\n");
}
krhino_sched_disable();
for (tmp = taskhead->next; tmp != taskend; tmp = tmp->next) {
tasknum ++;
}
taskinfo = krhino_mm_alloc(tasknum * sizeof(task_cpuusage_info));
if (taskinfo == NULL) {
krhino_sched_enable();
return;
}
memset(taskinfo, 0, tasknum * sizeof(task_cpuusage_info));
taskinfoeach = taskinfo;
for (tmp = taskhead->next; tmp != taskend; tmp = tmp->next) {
task = krhino_list_entry(tmp, ktask_t, task_stats_item);
if (task->task_name != NULL) {
task_name = task->task_name;
} else {
task_name = "anonym";
}
taskinfoeach->task_cpu_usage = debug_task_cpu_usage_get(task);
strncpy(taskinfoeach->task_name, task_name, sizeof(taskinfoeach->task_name) - 1);
taskinfoeach++;
}
krhino_sched_enable();
for (i = 0; i < tasknum; i++) {
taskinfoeach = taskinfo + i;
task_name = taskinfoeach->task_name;
task_cpu_usage = taskinfoeach->task_cpu_usage;
if (cpuusage_record != NULL) {
for (j = RHINO_CONFIG_CPU_NUM; j < record_len; j++) {
if (cpuusage_record[j].taskname[0] == 0) {
if (strlen(taskinfoeach->task_name) > CPU_USAGE_MAX_TASKNAME_LEN) {
aos_cli_printf("task name is longer than CPU_USAGE_MAX_TASKNAME_LEN\r\n");
break;
}
memcpy(cpuusage_record[j].taskname, taskinfoeach->task_name, strlen(taskinfoeach->task_name));
}
if (strcmp((char *)cpuusage_record[j].taskname, taskinfoeach->task_name) != 0) {
continue;
}
cpuusage_record[j].cpuusage[index] = (float)task_cpu_usage / 100;
break;
}
} else {
aos_cli_printf("%-19s%3d.%02d\r\n", task_name, (int)task_cpu_usage / 100,
(int)task_cpu_usage % 100);
}
}
krhino_mm_free(taskinfo);
if (cpuusage_record == NULL) {
aos_cli_printf("---------------------------\r\n");
}
}
/* one in ten thousand */
uint32_t debug_task_cpu_usage_get(ktask_t *task)
{
uint32_t task_cpu_usage = 0;
if (task_cpu_usage_period == 0) {
return 0;
}
task_cpu_usage = (uint64_t)(task->task_exec_time) * 10000 / task_cpu_usage_period;
if (task_cpu_usage > 10000) {
task_cpu_usage = 10000;
}
return task_cpu_usage;
}
/* one in ten thousand */
uint32_t debug_total_cpu_usage_get(uint32_t cpuid)
{
uint32_t total_cpu_usage = 0;
total_cpu_usage = 10000 - debug_task_cpu_usage_get(&g_idle_task[cpuid]);
return total_cpu_usage;
}
void cpuusage_statistics(void *arg)
{
ktask_t *cur_task;
kstat_t status;
uint32_t period = 0;
uint32_t total = 0;
int32_t stat_count = 0;
int32_t index = 0;
struct statistics_param *param = (struct statistics_param *)arg;
/* used for record to file */
int fd = -1;
int i;
#if DEBUG_CPUUSAGE_RECODE_TO_FILE_ENABLE
int j;
int ret = -1;
char buf[CPU_USAGE_MAX_TASKNAME_LEN + 1];
#endif
struct cpuusage_data cpuusage_record[DEBUG_CPUUSAGE_MAX_TASK];
period = param->period;
total = param->total;
stat_count = total / period;
#if DEBUG_CPUUSAGE_RECODE_TO_FILE_ENABLE
if (param->record_to_file == 1) {
for (i = 0; i < DEBUG_CPUUSAGE_MAX_TASK; i++) {
memset(cpuusage_record[i].taskname, 0, CPU_USAGE_MAX_TASKNAME_LEN);
cpuusage_record[i].cpuusage = krhino_mm_alloc(stat_count * sizeof(float));
memset(cpuusage_record[i].cpuusage, 0, stat_count * sizeof(float));
}
}
#endif
aos_cli_printf("Start to statistics CPU utilization, period %d ms\r\n", (int)period);
if (total != 0) {
aos_cli_printf("Total statistical time %d ms\r\n", (int)total);
}
debug_task_cpu_usage_stats();
status = krhino_task_sleep(period * RHINO_CONFIG_TICKS_PER_SECOND / 1000);
if (status == RHINO_TASK_CANCELED) {
//krhino_task_cancel_clr();
}
/* If total is 0, it will run continuously */
while ((index < stat_count) || (total == 0)) {
if (krhino_task_cancel_chk() == RHINO_TRUE) {
cur_task = krhino_cur_task_get();
krhino_task_dyn_del(cur_task);
}
debug_task_cpu_usage_stats();
status = krhino_task_sleep(period * RHINO_CONFIG_TICKS_PER_SECOND / 1000);
if (status == RHINO_TASK_CANCELED) {
//krhino_task_cancel_clr();
break;
} else {
if (param->record_to_file == 1) {
#if DEBUG_CPUUSAGE_RECODE_TO_FILE_ENABLE
debug_total_cpu_usage_show(cpuusage_record, DEBUG_CPUUSAGE_MAX_TASK, index);
#endif
} else {
debug_total_cpu_usage_show(NULL, 0, 0);
}
index++;
}
}
#if DEBUG_CPUUSAGE_RECODE_TO_FILE_ENABLE
if (param->record_to_file == 1) {
fd = open(DEBUG_CPUUSAGE_FILE_NAME, O_CREAT | O_WRONLY | O_TRUNC, 0666);
if (fd < 0) {
aos_cli_printf("file open error %s, %d\r\n", __FILE__, __LINE__);
}
for (i = 0; i < DEBUG_CPUUSAGE_MAX_TASK; i++) {
if (cpuusage_record[i].taskname[0] == 0) {
break;
}
if (fd >= 0) {
ret = snprintf(buf, sizeof(buf), "%-30s", cpuusage_record[i].taskname);
if (ret > 0) {
write(fd, buf, ret);
}
} else {
aos_cli_printf("%-30s", cpuusage_record[i].taskname);
}
for (j = 0; j < stat_count; j++) {
if (fd >= 0) {
ret = snprintf(buf, sizeof(buf), "%7.2f", cpuusage_record[i].cpuusage[j]);
if (ret > 0) {
write(fd, buf, ret);
}
} else {
aos_cli_printf("%7.2f", cpuusage_record[i].cpuusage[j]);
}
}
if (fd >= 0) {
write(fd, "\r\n", sizeof("\r\n"));
} else {
aos_cli_printf("\r\n");
}
}
if (fd >= 0) {
close(fd);
}
for (i = 0; i < DEBUG_CPUUSAGE_MAX_TASK; i++) {
krhino_mm_free(cpuusage_record[i].cpuusage);
}
}
#endif
printf("====CPU utilization statistics end====\r\n");
if (sync_mode == 1) {
krhino_sem_give(&sync_sem);
}
}
void cpuusage_cmd(char *buf, int32_t len, int32_t argc, char **argv)
{
static struct statistics_param param = {.period = 0, .total = 0};
ktask_t *task_tmp = NULL;
int argv_index = 1;
memset(¶m, 0, sizeof(param));
while (argv_index < argc) {
if (0 == strcmp(argv[argv_index], "-d")) {
argv_index++;
if (argv_index < argc) {
param.period = atoi(argv[argv_index]);
if (param.period == 0) {
aos_cli_printf("warning -d parma is error\r\n");
} else {
argv_index++;
}
}
} else if (0 == strcmp(argv[argv_index], "-t")) {
argv_index++;
if (argv_index < argc) {
param.total = atoi(argv[argv_index]);
if (param.total == 0) {
aos_cli_printf("warning -t parma is error\r\n");
} else {
argv_index++;
}
}
} else if (0 == strcmp(argv[argv_index], "-f")) {
param.record_to_file = 1;
argv_index++;
} else if (0 == strcmp(argv[argv_index], "-e")) {
if (cpuusage_task != NULL) {
krhino_task_cancel(cpuusage_task);
}
cpuusage_task = NULL;
return;
} else if (0 == strcmp(argv[argv_index], "-s")) {
if (sync_mode == 0) {
if ((krhino_sem_create(&sync_sem, "cpuusage_sync", 0)) != RHINO_SUCCESS) {
aos_cli_printf("warning -s parma is error\r\n");
continue;
}
argv_index++;
sync_mode = 1;
}
} else {
/* unrecognized parameters */
argv_index++;
}
}
if (param.period == 0) {
param.period = 1000;
aos_cli_printf("use default param: period %dms\r\n", param.period);
}
if ((param.record_to_file == 1) && (param.total == 0)) {
param.total = 30000;
aos_cli_printf("use default param: total %dms\r\n", param.total);
}
task_tmp = debug_task_find("cpuusage");
if (task_tmp != NULL) {
return;
}
krhino_task_dyn_create(&cpuusage_task, "cpuusage", (void *)¶m, (uint8_t)CPU_USAGE_DEFAULT_PRI, 0, CPU_USAGE_STACK,
cpuusage_statistics, 1);
if (sync_mode == 1) {
krhino_sem_take(&sync_sem, RHINO_WAIT_FOREVER);
krhino_sem_del(&sync_sem);
sync_mode = 0;
}
}
static const struct cli_command dumpsys_cpuusage_cmd[] = {
{"cpuusage", "show cpu usage", cpuusage_cmd},
};
void debug_cpuusage_cmds_register(void)
{
int32_t ret;
ret = aos_cli_register_commands(dumpsys_cpuusage_cmd, sizeof(dumpsys_cpuusage_cmd) / sizeof(struct cli_command));
if (ret) {
printf("%s %d failed, ret = %d\r\n", __func__, __LINE__, ret);
}
}
#endif /* #if (RHINO_CONFIG_SYS_STATS > 0) */
#endif /* AOS_COMP_CLI */
| YifuLiu/AliOS-Things | components/debug/src/debug_cpuusage.c | C | apache-2.0 | 13,716 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef DEBUG_CPUUSAGE_H
#define DEBUG_CPUUSAGE_H
#ifdef __cplusplus
extern "C" {
#endif
#define CPU_USAGE_MAX_TASKNAME_LEN 32
struct cpuusage_data {
char taskname[CPU_USAGE_MAX_TASKNAME_LEN];
float *cpuusage;
};
void debug_task_cpu_usage_stats(void);
uint32_t debug_task_cpu_usage_get(ktask_t *task);
uint32_t debug_total_cpu_usage_get(uint32_t cpuid);
void debug_total_cpu_usage_show(struct cpuusage_data *cpuusage_record, int32_t record_len, int32_t index);
kstat_t debug_task_cpu_usage_init(void);
void debug_cpuusage_cmds_register(void);
#ifdef __cplusplus
}
#endif
#endif /* DEBUG_CPUUSAGE_H */
| YifuLiu/AliOS-Things | components/debug/src/debug_cpuusage.h | C | apache-2.0 | 693 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#if AOS_COMP_CLI
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include "aos/cli.h"
#include "debug_api.h"
typedef struct {
char task_name[32];
uint32_t task_id;
uint32_t task_state;
uint32_t stack_size;
size_t free_size;
uint64_t time_total;
uint8_t task_prio;
char candidate;
#if (RHINO_CONFIG_CPU_NUM > 1)
uint8_t cpu_binded;
uint8_t cpu_num;
uint8_t cur_exc;
#endif
} dumpsys_task_info_t;
#define MM_LEAK_CHECK_ROUND_SCOND 10 * 1000
#define RHINO_BACKTRACE_DEPTH 10
ktimer_t g_mm_leak_check_timer;
uint32_t dumpsys_task_func(char *buf, uint32_t len, int32_t detail)
{
kstat_t rst;
size_t free_size = 0;
uint64_t time_total = 0;
/* consistent with "task_stat_t" */
char *cpu_stat[] = { "ERROR", "RDY", "PEND", "SUS",
"PEND_SUS", "SLP", "SLP_SUS", "DELETED"
};
klist_t *taskhead = &g_kobj_list.task_head;
klist_t *taskend = taskhead;
klist_t *tmp;
ktask_t *task;
size_t corenum;
(void)corenum;
#if (RHINO_CONFIG_CPU_NUM > 1)
ktask_t *candidate[RHINO_CONFIG_CPU_NUM];
#else
ktask_t *candidate;
#endif
char yes = 'N';
int32_t taskstate = 0;
int32_t tasknum = 0;
int32_t taskindex = 0;
dumpsys_task_info_t *taskinfo;
dumpsys_task_info_t *taskinfoeach;
aos_cli_printf("-----------------------------------------------------------"
"---------------------\r\n");
krhino_sched_disable();
#if (RHINO_CONFIG_CPU_NUM > 1)
for (corenum = 0; corenum < RHINO_CONFIG_CPU_NUM; corenum++) {
preferred_cpu_ready_task_get(&g_ready_queue, corenum);
candidate[corenum] = g_preferred_ready_task[corenum];
}
#else
preferred_cpu_ready_task_get(&g_ready_queue, cpu_cur_get());
candidate = g_preferred_ready_task[cpu_cur_get()];
#endif
for (tmp = taskhead->next; tmp != taskend; tmp = tmp->next) {
tasknum ++;
}
taskinfo = malloc(tasknum * sizeof(dumpsys_task_info_t));
if (taskinfo == NULL) {
krhino_sched_enable();
return RHINO_NO_MEM;
}
memset(taskinfo, 0, tasknum * sizeof(dumpsys_task_info_t));
for (tmp = taskhead->next; tmp != taskend; tmp = tmp->next) {
char name_cut[19];
taskinfoeach = taskinfo + taskindex;
taskindex++;
task = krhino_list_entry(tmp, ktask_t, task_stats_item);
const name_t *task_name;
rst = krhino_task_stack_min_free(task, &free_size);
if (rst != RHINO_SUCCESS) {
free_size = 0;
}
#if (RHINO_CONFIG_SYS_STATS > 0)
time_total = task->task_time_total_run / 20;
#endif
if (task->task_name != NULL) {
task_name = task->task_name;
} else {
task_name = "anonym";
}
strncpy(taskinfoeach->task_name, task_name, sizeof(taskinfoeach->task_name) - 1);
taskinfoeach->task_id = task->task_id;
#if (RHINO_CONFIG_CPU_NUM > 1)
for (corenum = 0; corenum < RHINO_CONFIG_CPU_NUM; corenum++) {
if (candidate[corenum] == task) {
yes = 'Y';
} else {
yes = 'N';
}
}
#else
if (candidate == task) {
yes = 'Y';
} else {
yes = 'N';
}
#endif
taskstate = task->task_state >= sizeof(cpu_stat) / sizeof(cpu_stat[0])
? 0
: task->task_state;
taskinfoeach->task_state = taskstate;
taskinfoeach->task_prio = task->prio;
taskinfoeach->stack_size = task->stack_size * sizeof(cpu_stack_t);
taskinfoeach->free_size = free_size * sizeof(cpu_stack_t);
taskinfoeach->time_total = time_total;
taskinfoeach->candidate = yes;
#if (RHINO_CONFIG_CPU_NUM > 1)
taskinfoeach->cpu_binded = task->cpu_binded;
taskinfoeach->cpu_num = task->cpu_num;
taskinfoeach->cur_exc = task->cur_exc;
#endif
/* if not support %-N.Ms,cut it manually */
if (strlen(task_name) > 18) {
memset(name_cut, 0, sizeof(name_cut));
memcpy(name_cut, task->task_name, 18);
task_name = name_cut;
strncpy(taskinfoeach->task_name, task_name, strlen(task_name));
}
}
krhino_sched_enable();
#if (RHINO_CONFIG_CPU_NUM > 1)
aos_cli_printf("Name ID State Prio StackSize MinFreesize "
"Runtime Candidate cpu_binded cpu_num cur_exc\r\n");
#else
aos_cli_printf("Name ID State Prio StackSize MinFreesize "
"Runtime Candidate\r\n");
#endif
aos_cli_printf("-----------------------------------------------------------"
"---------------------\r\n");
for (taskindex = 0; taskindex < tasknum; taskindex++) {
taskinfoeach = taskinfo + taskindex;
#if (RHINO_CONFIG_CPU_NUM > 1)
aos_cli_printf("%-19s%-6d%-9s%-5d%-10d%-12u%-9u %-11c%-10d%-10d%-10d\r\n",
taskinfoeach->task_name, taskinfoeach->task_id, cpu_stat[taskinfoeach->task_state],
taskinfoeach->task_prio, taskinfoeach->stack_size,
taskinfoeach->free_size, (uint32_t)taskinfoeach->time_total,
taskinfoeach->candidate, taskinfoeach->cpu_binded,
taskinfoeach->cpu_num, taskinfoeach->cur_exc);
#else
aos_cli_printf("%-19s%-6d%-9s%-5d%-10d%-12u%-9u %-11c \r\n",
taskinfoeach->task_name, taskinfoeach->task_id, cpu_stat[taskinfoeach->task_state],
taskinfoeach->task_prio, (int32_t)taskinfoeach->stack_size,
taskinfoeach->free_size, (uint32_t)taskinfoeach->time_total,
taskinfoeach->candidate);
#endif
}
free(taskinfo);
aos_cli_printf("-----------------------------------------------------------"
"---------------------\r\n");
return RHINO_SUCCESS;
}
static void task_cmd(char *buf, int32_t len, int32_t argc, char **argv)
{
dumpsys_task_func(NULL, 0, 1);
}
static void dumpsys_cmd(char *buf, int len, int argc, char **argv)
{
if (argc != 2) {
aos_cli_printf("dumpsys help:\r\n");
aos_cli_printf("dumpsys mm : show kernel memory status.\r\n");
#if (RHINO_CONFIG_MM_DEBUG > 0)
aos_cli_printf("dumpsys mm_info : show kernel memory has alloced.\r\n");
#endif
return;
}
if (0 == strcmp(argv[1], "mm")) {
debug_mm_overview(aos_cli_printf);
}
#if (RHINO_CONFIG_MM_DEBUG > 0)
else if (0 == strcmp(argv[1], "mm_info")) {
dumpsys_mm_info_func(0);
}
#endif
}
static void task_bt(char *buf, int32_t len, int32_t argc, char **argv)
{
uint32_t task_id;
ktask_t *task;
switch (argc) {
case 2:
task_id = (uint32_t)strtoul(argv[1], 0, 10);
break;
default:
aos_cli_printf("taskbt <taskid>\r\n"
"taskid : task id\r\n");
return;
}
task = debug_task_find_by_id(task_id);
if (task == NULL) {
aos_cli_printf("taskid %d not exist\r\n", task_id);
return;
}
if (((ktask_t *)task)->task_name) {
aos_cli_printf("task name : %s\r\n", ((ktask_t *)task)->task_name);
debug_backtrace_task((char *)(((ktask_t *)task)->task_name), aos_cli_printf);
}
}
static void task_btn(char *buf, int32_t len, int32_t argc, char **argv)
{
if (argc == 2) {
debug_backtrace_task(argv[1], aos_cli_printf);
} else {
aos_cli_printf("taskbtn <taskname>\r\n");
}
}
#if (RHINO_CONFIG_MM_DEBUG > 0)
static void mem_leak(char *buf, int32_t len, int32_t argc, char **argv)
{
static int call_cnt = 0;
int query_index = -1;
if (call_cnt == 0) {
aos_cli_printf("memory leak check start.\r\n");
}
if (argc == 2) {
query_index = strtoul(argv[1], NULL, 0);
if (query_index > call_cnt) {
query_index = -1;
}
} else {
call_cnt++;
printf("\r\nAdd tag %d when malloc\r\n", call_cnt);
}
dumpsys_mm_leakcheck(call_cnt, query_index);
}
#endif
static const struct cli_command dumpsys_cli_cmd[] = {
{ "tasklist", "list all thread info", task_cmd },
{ "dumpsys", "dump system info", dumpsys_cmd },
{ "taskbt", "list thread backtrace", task_bt },
{ "taskbtn", "list thread backtrace by name", task_btn },
#if (RHINO_CONFIG_MM_DEBUG > 0)
{ "mmlk", "memory leak info", mem_leak },
#endif
};
void debug_dumpsys_cmds_register(void)
{
int32_t ret;
ret = aos_cli_register_commands(dumpsys_cli_cmd, sizeof(dumpsys_cli_cmd) / sizeof(struct cli_command));
if (ret) {
printf("%s %d failed, ret = %d\r\n", __func__, __LINE__, ret);
}
}
#endif /* AOS_COMP_CLI */
| YifuLiu/AliOS-Things | components/debug/src/debug_dumpsys.c | C | apache-2.0 | 8,976 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef DEBUG_DUMPSYS_H
#define DEBUG_DUMPSYS_H
#ifdef __cplusplus
extern "C"
{
#endif
void debug_dumpsys_cmds_register(void);
#ifdef __cplusplus
}
#endif
#endif /* DEBUG_DUMPSYS_H */
| YifuLiu/AliOS-Things | components/debug/src/debug_dumpsys.h | C | apache-2.0 | 253 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include "debug_api.h"
ktask_t *debug_task_find(char *name)
{
#if (RHINO_CONFIG_KOBJ_LIST > 0)
klist_t *listnode;
ktask_t *task;
for (listnode = g_kobj_list.task_head.next;
listnode != &g_kobj_list.task_head; listnode = listnode->next) {
task = krhino_list_entry(listnode, ktask_t, task_stats_item);
if (0 == strcmp(name, task->task_name)) {
return task;
}
}
#endif
return NULL;
}
ktask_t *debug_task_find_running(char **name)
{
ktask_t *task_running;
task_running = g_active_task[cpu_cur_get()];
if (task_running != NULL && name != NULL) {
*name = (char *)task_running->task_name;
}
return task_running;
}
ktask_t *debug_task_find_by_id(uint32_t task_id)
{
#if (RHINO_CONFIG_KOBJ_LIST > 0)
klist_t *listnode;
ktask_t *task;
for (listnode = g_kobj_list.task_head.next;
listnode != &g_kobj_list.task_head; listnode = listnode->next) {
task = krhino_list_entry(listnode, ktask_t, task_stats_item);
if (task->task_id == task_id) {
return task;
}
}
#endif
return NULL;
}
/* return:
0 not ready
1 ready but not running
2 running but interrupted
3 running*/
int debug_task_is_running(ktask_t *task)
{
int i;
for (i = 0; i < RHINO_CONFIG_CPU_NUM; i++) {
if (g_active_task[i] == task
&& g_intrpt_nested_level[i] == 0) {
return 3;
} else if (g_active_task[i] == task) {
return 2;
}
}
if (task->task_state == K_RDY) {
return 1;
} else {
return 0;
}
}
uint32_t debug_task_id_now()
{
if (g_active_task[cpu_cur_get()] == NULL || g_intrpt_nested_level[cpu_cur_get()] != 0) {
return 0;
}
return g_active_task[cpu_cur_get()]->task_id;
}
void *debug_task_stack_bottom(ktask_t *task)
{
if (task == NULL) {
task = g_active_task[cpu_cur_get()];
}
if (task->task_state == K_DELETED) {
return NULL;
}
#if (RHINO_CONFIG_CPU_STACK_DOWN > 0)
return task->task_stack_base + task->stack_size;
#else
return task->task_stack_base;
#endif
}
| YifuLiu/AliOS-Things | components/debug/src/debug_infoget.c | C | apache-2.0 | 2,222 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef DEBUG_INFOGET_H
#define DEBUG_INFOGET_H
#ifdef __cplusplus
extern "C" {
#endif
/**
* This function will get task handle by its name.
*/
ktask_t *debug_task_find(char *name);
/**
* This function will return the running task and its name.
*/
ktask_t *debug_task_find_running(char **name);
/**
* This function will get task handle by its id.
*/
ktask_t *debug_task_find_by_id(uint32_t task_id);
/**
* This function will return true if task is running.
*/
int debug_task_is_running(ktask_t *task);
/**
* This function will return the running task_id, 0 means isr
*/
uint32_t debug_task_id_now();
/**
* This function will get the bottom of task stack
* @param[in] task NULL for active task
* @return the bottom of stack
*/
void *debug_task_stack_bottom(ktask_t *task);
#ifdef __cplusplus
}
#endif
#endif /* DEBUG_INFOGET_H */
| YifuLiu/AliOS-Things | components/debug/src/debug_infoget.h | C | apache-2.0 | 920 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdarg.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include "debug_api.h"
#define MIN(x,y) (((x)<(y))?(x):(y))
#if DEBUG_LAST_WORD_ENABLE
#ifdef CONFIG_VFS_LSOPEN
static void debug_paniclog_to_file(void);
#endif
static int panic_header_init(debug_panic_info_head_t *panic_header);
static int panic_header_show(debug_panic_info_head_t *panic_header);
static int panic_header_set(debug_panic_info_head_t *panic_header);
static int panic_header_get(debug_panic_info_head_t *panic_header);
static int panic_log_set(uint8_t *info, uint32_t len);
static int panic_log_get(uint8_t *info_buffer, uint32_t len);
static void panic_log_clean(void);
__attribute__((weak)) int clear_silent_reboot_flag(void)
{
return 0;
}
__attribute__((weak)) int set_silent_reboot_flag(void)
{
return 0;
}
__attribute__((weak)) void k_dcache_clean(uint32_t addr, uint32_t len)
{
return;
}
/* set ram attributes for some mcu*/
__attribute__((weak)) void alios_debug_lastword_init_hook()
{
return;
}
#define HEADER_START_ADDR (DEBUG_LASTWORD_RAM_ADDR)
#define LOG_START_ADDR (DEBUG_LASTWORD_RAM_ADDR + sizeof(debug_panic_info_head_t))
#define LOG_REGION_LEN (DEBUG_LASTWORD_REGION_LEN - sizeof(debug_panic_info_head_t))
#define LOG_END_ADDR (DEBUG_LASTWORD_RAM_ADDR + DEBUG_LASTWORD_REGION_LEN)
#define CRC_CALC_LEN (uint32_t)(&(((debug_panic_info_head_t *)0)->crc16))
static debug_panic_info_head_t panic_header_buffer;
#define POLY 0x1021
uint16_t crc16_calc(uint8_t *addr, uint32_t num, uint16_t crc)
{
int i;
for (; num > 0; num--) {
crc = crc ^ (*addr++ << 8);
for (i = 0; i < 8; i++) {
if (crc & 0x8000) {
crc = (crc << 1) ^ POLY;
} else {
crc <<= 1;
}
}
crc &= 0xFFFF;
}
return (crc);
}
void debug_lastword_init(void)
{
printf("init lastword\r\n");
#ifdef CONFIG_VFS_LSOPEN
mkdir(DEBUG_LOG_DIR_NAME, 0777);
#endif
panic_header_get(&panic_header_buffer);
if (crc16_calc((uint8_t *)&panic_header_buffer, CRC_CALC_LEN, 0xffff) != panic_header_buffer.crc16) {
panic_header_init(&panic_header_buffer);
panic_header_set(&panic_header_buffer);
panic_log_clean();
printf("[Error] lastword: init crc fail!\r\n");
return;
}
printf("lastword: CRC check is OK\r\n");
#ifdef CONFIG_VFS_LSOPEN
if (panic_header_buffer.log_magic == DEBUG_PANIC_LOG_MAGIC) {
char path[64];
int fd = -1;
printf("lastword: try to read lastword to file!\r\n");
/* open /data/smartbox_abort as a flag for panic */
memset(path, 0, sizeof(path));
snprintf(path, sizeof(path) - 1, "/data/smartbox_abort");
fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0666);
if (fd < 0) {
printf("open panic flag file fail\r\n");
} else {
printf("open panic flag file fd %d\r\n", fd);
close(fd);
}
printf("store panic log to file\r\n");
debug_paniclog_to_file();
}
#endif
panic_log_clean();
panic_header_buffer.log_magic = 0;
if (panic_header_buffer.header_magic != DEBUG_PANIC_HEADER_MAGIC) {
panic_header_init(&panic_header_buffer);
} else {
panic_header_buffer.reboot_sum_count++;
}
panic_header_show(&panic_header_buffer);
panic_header_set(&panic_header_buffer);
clear_silent_reboot_flag();
alios_debug_lastword_init_hook();
}
void debug_reboot_reason_update(unsigned int reason)
{
int ret = -1;
static int reason_id_update_flag = 0;
panic_header_get(&panic_header_buffer);
if (reason_id_update_flag == 0) {
panic_header_buffer.reboot_reason_id++;
reason_id_update_flag = 1;
}
panic_header_buffer.reboot_reason = reason;
if ((DEBUG_REBOOT_REASON_PANIC == reason) || (DEBUG_REBOOT_REASON_FATAL_ERR == reason)) {
set_silent_reboot_flag();
panic_header_buffer.runtime_before_painc[panic_header_buffer.runtime_record_id] = krhino_ticks_to_ms(
krhino_sys_tick_get());
panic_header_buffer.runtime_record_id++;
if (panic_header_buffer.runtime_record_id >= RUNTIME_COUNT) {
panic_header_buffer.runtime_record_id = 0;
}
panic_header_buffer.panic_count++;
}
ret = panic_header_set(&panic_header_buffer);
if (ret) {
print_str("reboot reason set err\n");
}
}
unsigned int debug_reboot_reason_get()
{
panic_header_get(&panic_header_buffer);
if (panic_header_buffer.header_magic != DEBUG_PANIC_HEADER_MAGIC) {
panic_header_init(&panic_header_buffer);
panic_header_set(&panic_header_buffer);
return DEFAULT_REBOOT_REASON;
}
if (panic_header_buffer.reboot_sum_count > panic_header_buffer.reboot_reason_id) {
panic_header_buffer.reboot_reason_id = panic_header_buffer.reboot_sum_count;
panic_header_buffer.reboot_reason = DEBUG_REBOOT_UNKNOWN_REASON;
panic_header_set(&panic_header_buffer);
return DEBUG_REBOOT_UNKNOWN_REASON;
}
return panic_header_buffer.reboot_reason;
}
int64_t debug_get_painc_runtime(int panic_count, int *real_panic_count)
{
int32_t idx = 0, count = 0;
int64_t duration = 0;
panic_header_get(&panic_header_buffer);
if (panic_header_buffer.header_magic != DEBUG_PANIC_HEADER_MAGIC) {
panic_header_init(&panic_header_buffer);
panic_header_set(&panic_header_buffer);
*real_panic_count = 0;
return -1;
}
if (panic_header_buffer.panic_count == 0) {
*real_panic_count = 0;
return -1;
}
if (panic_count > RUNTIME_COUNT) {
printf("panic count is larger than %d\r\n", RUNTIME_COUNT);
}
idx = panic_header_buffer.runtime_record_id;
for (count = 0; count < RUNTIME_COUNT; count++) {
if (count >= panic_count) {
break;
}
idx--;
if (idx < 0) {
idx = RUNTIME_COUNT - 1;
}
if (panic_header_buffer.runtime_before_painc[idx] != -1) {
duration += panic_header_buffer.runtime_before_painc[idx];
} else {
break;
}
}
*real_panic_count = count;
return duration;
}
#ifdef CONFIG_VFS_LSOPEN
static void debug_paniclog_to_file(void)
{
int i = 0, index = 0;
int fd = -1, indexfile_fd = -1;
char path[64];
char info_buffer[128], index_buffer[10];
int len;
if (panic_header_buffer.log_magic != DEBUG_PANIC_LOG_MAGIC) {
return;
}
for (i = 0; i < DEBUG_LOG_FILE_NUM; i++) {
memset(path, 0, sizeof(path));
snprintf(path, sizeof(path), "%s_%02d", DEBUG_LOG_FILE_NAME, i);
/* if file not exit, create it, and output debug info to it */
if (access(path, R_OK) != 0) {
fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0666);
if (fd >= 0) {
break;
}
}
}
if (i == DEBUG_LOG_FILE_NUM) {
if (access(DEBUG_LOG_FILE_INDEX_NAME, R_OK) != 0) {
indexfile_fd = open(DEBUG_LOG_FILE_INDEX_NAME, O_CREAT | O_WRONLY | O_TRUNC, 0666);
index = 0;
} else {
indexfile_fd = open(DEBUG_LOG_FILE_INDEX_NAME, O_CREAT | O_RDWR, 0666);
read(indexfile_fd, index_buffer, sizeof(index_buffer));
sscanf(index_buffer, "%02d", &index);
if ((index < 0) || (index >= DEBUG_LOG_FILE_NUM)) {
index = 0;
} else {
index++;
if (index >= DEBUG_LOG_FILE_NUM) {
index = 0;
}
}
lseek(indexfile_fd, SEEK_SET, 0);
}
if (indexfile_fd >= 0) {
memset(index_buffer, 0, sizeof(index_buffer));
len = snprintf(index_buffer, sizeof(index_buffer), "%02d", index);
write(indexfile_fd, index_buffer, len);
close(indexfile_fd);
}
memset(path, 0, sizeof(path));
snprintf(path, sizeof(path), "%s_%02d", DEBUG_LOG_FILE_NAME, index);
fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0666);
}
if (fd < 0) {
printf("open file %s error, %s, %d\r\n", path, __FILE__, __LINE__);
return;
}
while (1) {
len = sizeof(info_buffer);
len = panic_log_get((uint8_t *)info_buffer, len);
if (len <= 0) {
break;
}
len = write(fd, info_buffer, len);
if (len < 0) {
printf("write file %s error, %s, %d\r\n", path, __FILE__, __LINE__);
//break;
}
}
close(fd);
fd = -1;
return;
}
#endif
static int panic_header_init(debug_panic_info_head_t *panic_header)
{
uint32_t i;
panic_header->header_magic = DEBUG_PANIC_HEADER_MAGIC;
panic_header->log_magic = 0;
panic_header->reboot_reason = DEFAULT_REBOOT_REASON;
panic_header->reboot_sum_count = 0;
panic_header->reboot_reason_id = 0;
panic_header->panic_count = 0;
panic_header->runtime_record_id = 0;
for (i = 0; i < RUNTIME_COUNT; i++) {
panic_header->runtime_before_painc[i] = -1;
}
return 0;
}
static int panic_header_show(debug_panic_info_head_t *panic_header)
{
printf("===========show panic header===========\r\n");
printf("panic header reboot reason %d\r\n", (int)panic_header->reboot_reason);
printf("panic header reboot sum count %d\r\n", (int)panic_header->reboot_sum_count);
printf("panic header reboot reason reason id %d\r\n", (int)panic_header->reboot_reason_id);
printf("panic header panic count %d\r\n", (int)panic_header->panic_count);
printf("===========end===========\r\n");
return 0;
}
static int panic_header_set(debug_panic_info_head_t *panic_header)
{
if (panic_header == NULL) {
return -1;
}
debug_panic_info_head_t *log_header = (debug_panic_info_head_t *)HEADER_START_ADDR;
/* calculate the crc */
panic_header->crc16 = crc16_calc((uint8_t *)panic_header, CRC_CALC_LEN, 0xffff);
memcpy(log_header, panic_header, sizeof(debug_panic_info_head_t));
k_dcache_clean((uintptr_t)log_header, sizeof(debug_panic_info_head_t));
return 0;
}
static int panic_header_get(debug_panic_info_head_t *panic_header)
{
if (panic_header == NULL) {
return -1;
}
debug_panic_info_head_t *log_header = (debug_panic_info_head_t *)HEADER_START_ADDR;
memcpy(panic_header, log_header, sizeof(debug_panic_info_head_t));
return 0;
}
static int panic_log_set(uint8_t *info, uint32_t len)
{
if ((info == NULL) || (len == 0)) {
return -1;
}
static uint8_t *log_ram_addr_cur = (uint8_t *)LOG_START_ADDR;
if ((uintptr_t)(len + log_ram_addr_cur) <= (uintptr_t)LOG_END_ADDR) {
memcpy(log_ram_addr_cur, info, len);
k_dcache_clean((uintptr_t)log_ram_addr_cur, len);
log_ram_addr_cur += len;
return 0;
}
return -1;
}
static int panic_log_get(uint8_t *info_buffer, uint32_t len)
{
if (info_buffer == NULL) {
return -1;
}
static uint8_t *log_ram_addr_cur = (uint8_t *)LOG_START_ADDR;
int32_t len_tmp;
if (log_ram_addr_cur >= (uint8_t *)LOG_END_ADDR) {
return -1;
}
len = MIN(len, (uint8_t *)LOG_END_ADDR - log_ram_addr_cur);
memcpy(info_buffer, log_ram_addr_cur, len);
log_ram_addr_cur += len;
len_tmp = len - 1;
while (len_tmp >= 0) {
if (info_buffer[len_tmp] != 0) {
break;
}
len--;
len_tmp--;
}
return len;
}
static void panic_log_clean(void)
{
static uint8_t *log_ram_addr_cur = (uint8_t *)LOG_START_ADDR;
memset(log_ram_addr_cur, 0, LOG_REGION_LEN);
}
int print_str(const char *fmt, ...)
{
int ret = -1;
char strbuf[400];
va_list args;
va_start(args, fmt);
ret = vsnprintf((char *)strbuf, sizeof(strbuf) - 1, fmt, args);
va_end(args);
if (ret > 0) {
panic_log_set((uint8_t *)strbuf, ret);
if (panic_header_buffer.log_magic != DEBUG_PANIC_LOG_MAGIC) {
panic_header_buffer.log_magic = DEBUG_PANIC_LOG_MAGIC;
panic_header_set(&panic_header_buffer);
}
}
return ret;
}
int vprint_str(const char *fmt, va_list ap)
{
int ret = -1;
char strbuf[400];
ret = vsnprintf((char *)strbuf, sizeof(strbuf) - 1, fmt, ap);
if (ret > 0) {
panic_log_set((uint8_t *)strbuf, ret);
if (panic_header_buffer.log_magic != DEBUG_PANIC_LOG_MAGIC) {
panic_header_buffer.log_magic = DEBUG_PANIC_LOG_MAGIC;
panic_header_set(&panic_header_buffer);
}
}
return ret;
}
#endif
| YifuLiu/AliOS-Things | components/debug/src/debug_lastword.c | C | apache-2.0 | 12,857 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef DEBUG_LASTWORD_H
#define DEBUG_LASTWORD_H
#ifdef __cplusplus
extern "C" {
#endif
#define DEBUG_PANIC_HEADER_MAGIC 0xdeba5a5aa5a5abed
#define DEBUG_PANIC_LOG_MAGIC 0xdeba5a5aa5a5abed
#define DEFAULT_REBOOT_REASON 0x01
#define RUNTIME_COUNT 20
typedef struct {
uint64_t header_magic;
uint32_t reboot_reason_id;
uint32_t reboot_sum_count;
uint32_t reboot_reason;
uint32_t panic_count; /* record info of runtime before panic */
uint32_t runtime_record_id;
int64_t runtime_before_painc[RUNTIME_COUNT];
uint64_t log_magic;
uint16_t crc16;
} debug_panic_info_head_t;
int print_str(const char *fmt, ...);
int vprint_str(const char *fmt, va_list ap);
void debug_lastword_init(void);
void debug_reboot_reason_update(unsigned int reason);
unsigned int debug_reboot_reason_get(void);
int64_t debug_get_painc_runtime(int panic_count, int *real_panic_count);
#ifdef __cplusplus
}
#endif
#endif /* DEBUG_LASTWORD_H */
| YifuLiu/AliOS-Things | components/debug/src/debug_lastword.h | C | apache-2.0 | 1,057 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include "k_api.h"
#include "debug_api.h"
/* convert int to ascii(HEX)
while using format % in libc, malloc/free is involved.
this function avoid using malloc/free. so it works when heap corrupt. */
char *k_int2str(int num, char *str)
{
char index[] = "0123456789ABCDEF";
unsigned int usnum = (unsigned int)num;
str[7] = index[usnum % 16];
usnum /= 16;
str[6] = index[usnum % 16];
usnum /= 16;
str[5] = index[usnum % 16];
usnum /= 16;
str[4] = index[usnum % 16];
usnum /= 16;
str[3] = index[usnum % 16];
usnum /= 16;
str[2] = index[usnum % 16];
usnum /= 16;
str[1] = index[usnum % 16];
usnum /= 16;
str[0] = index[usnum % 16];
usnum /= 16;
return str;
}
#if (K_MM_STATISTIC > 0)
void debug_mm_overview(int (*print_func)(const char *fmt, ...))
{
#if (RHINO_CONFIG_MM_BLK > 0)
mblk_info_t pool_info;
#endif
size_t max_free_blk_size = 0;
#if (RHINO_CONFIG_MM_TLF > 0)
max_free_blk_size = krhino_mm_max_free_size_get();
#endif
char s_heap_overview[] =
" | 0x | 0x | 0x | 0x | 0x |\r\n";
print_func(
"---------------------------------------------------------------------------\r\n");
print_func(
"[HEAP]| TotalSz | FreeSz | UsedSz | MinFreeSz | MaxFreeBlkSz |\r\n");
k_int2str((int)(g_kmm_head->free_size + g_kmm_head->used_size),
&s_heap_overview[10]);
k_int2str((int)g_kmm_head->free_size, &s_heap_overview[23]);
k_int2str((int)g_kmm_head->used_size, &s_heap_overview[36]);
k_int2str((int)(g_kmm_head->free_size + g_kmm_head->used_size -
g_kmm_head->maxused_size),
&s_heap_overview[49]);
k_int2str((int)max_free_blk_size, &s_heap_overview[62]);
print_func(s_heap_overview);
print_func(
"---------------------------------------------------------------------------\r\n");
#if (RHINO_CONFIG_MM_BLK > 0)
(void)krhino_mblk_info_nolock((mblk_pool_t *)g_kmm_head->fix_pool, &pool_info);
print_func(
"[POOL]| PoolSz | FreeSz | UsedSz | MinFreeSz | MaxFreeBlkSz |\r\n");
k_int2str((int)pool_info.pool_size, &s_heap_overview[10]);
k_int2str((int)(pool_info.pool_size - pool_info.used_size), &s_heap_overview[23]);
k_int2str((int)pool_info.used_size, &s_heap_overview[36]);
k_int2str((int)(pool_info.pool_size - pool_info.max_used_size), &s_heap_overview[49]);
k_int2str((int)pool_info.max_blk_size, &s_heap_overview[62]);
print_func(s_heap_overview);
print_func(
"---------------------------------------------------------------------------\r\n");
#endif
}
#else
void debug_mm_overview(int (*print_func)(const char *fmt, ...))
{
print_func("K_MM_STATISTIC in k_config.h is closed!\r\n");
}
#endif
#if (RHINO_CONFIG_KOBJ_LIST > 0)
static void debug_task_show(int (*print_func)(const char *fmt, ...), ktask_t *task)
{
size_t free_size;
int stat_idx;
int i;
int cpu_idx;
char *cpu_stat[] = { "UNK", "RDY", "PEND", "SUS",
"PEND_SUS", "SLP", "SLP_SUS", "DEL"
};
const name_t *task_name;
char s_task_overview[] = " 0x 0x "
" 0x (0x ) "
" \r\n";
if (krhino_task_stack_min_free(task, &free_size) != RHINO_SUCCESS) {
free_size = 0;
}
free_size *= sizeof(cpu_stack_t);
/* set name */
task_name = task->task_name == NULL ? "anonym" : task->task_name;
for (i = 0; i < 20; i++) {
s_task_overview[i] = ' ';
}
for (i = 0; i < strlen(task_name); i++) {
s_task_overview[i] = task_name[i];
}
/* set state */
stat_idx = task->task_state >= sizeof(cpu_stat) / sizeof(char *)
? 0
: task->task_state;
for (i = 21; i < 29; i++) {
s_task_overview[i] = ' ';
}
for (i = 21; i < 29; i++) {
if (cpu_stat[stat_idx][i - 21] == '\0') {
break;
}
s_task_overview[i] = cpu_stat[stat_idx][i - 21];
}
/* set stack priority */
k_int2str(task->prio, &s_task_overview[32]);
/* set stack info */
k_int2str((int)task->task_stack_base, &s_task_overview[43]);
k_int2str((int)task->stack_size * sizeof(cpu_stack_t),
&s_task_overview[54]);
k_int2str((int)free_size, &s_task_overview[65]);
cpu_idx = 65 + 17;
(void)cpu_idx;
#if (RHINO_CONFIG_CPU_NUM > 1)
s_task_overview[cpu_idx] = (uint8_t)('0' + task->cpu_binded);
s_task_overview[cpu_idx + 12] = (uint8_t)('0' + task->cpu_num);
s_task_overview[cpu_idx + 23] = (uint8_t)('0' + task->cur_exc);
#endif
/* print */
if (print_func == NULL) {
print_func = printf;
}
print_func(s_task_overview);
}
void debug_task_overview(int (*print_func)(const char *fmt, ...))
{
klist_t *listnode;
ktask_t *task;
print_func("---------------------------------------------------------------"
"-----------\r\n");
#if (RHINO_CONFIG_CPU_NUM > 1)
print_func("TaskName State Prio Stack StackSize "
"(MinFree) cpu_binded cpu_num cur_exc\r\n");
#else
print_func("TaskName State Prio Stack StackSize "
"(MinFree)\r\n");
#endif
print_func("---------------------------------------------------------------"
"-----------\r\n");
for (listnode = g_kobj_list.task_head.next;
listnode != &g_kobj_list.task_head; listnode = listnode->next) {
task = krhino_list_entry(listnode, ktask_t, task_stats_item);
debug_task_show(print_func, task);
}
}
#else
void debug_task_overview(int (*print_func)(const char *fmt, ...))
{
print_func("RHINO_CONFIG_KOBJ_LIST in k_config.h is closed!\r\n");
}
#endif /* #if (RHINO_CONFIG_KOBJ_LIST > 0) */
#if (RHINO_CONFIG_BUF_QUEUE > 0)
#if (RHINO_CONFIG_KOBJ_LIST > 0)
void debug_buf_queue_overview(int (*print_func)(const char *fmt, ...))
{
int i;
klist_t *listnode, *task_listnode;
ktask_t *task;
kbuf_queue_t *buf_queue;
const name_t *task_name;
char s_buf_queue_overview[] = "0x 0x 0x 0x "
"0x \r\n";
print_func("------------------------------------------------------------------\r\n");
print_func("BufQueAddr TotalSize PeakNum CurrNum MinFreeSz TaskWaiting\r\n");
print_func("------------------------------------------------------------------\r\n");
for (listnode = g_kobj_list.buf_queue_head.next;
listnode != &g_kobj_list.buf_queue_head; listnode = listnode->next) {
buf_queue = krhino_list_entry(listnode, kbuf_queue_t, buf_queue_item);
if (buf_queue->blk_obj.obj_type != RHINO_BUF_QUEUE_OBJ_TYPE) {
print_func("BufQueue Type error!\r\n");
break;
}
/* set buf_queue information */
k_int2str((int)buf_queue, &s_buf_queue_overview[2]);
k_int2str((int)(buf_queue->ringbuf.end - buf_queue->ringbuf.buf),
&s_buf_queue_overview[13]);
k_int2str((int)buf_queue->peak_num, &s_buf_queue_overview[24]);
k_int2str((int)buf_queue->cur_num, &s_buf_queue_overview[35]);
k_int2str((int)buf_queue->min_free_buf_size, &s_buf_queue_overview[46]);
/* print */
print_func(s_buf_queue_overview);
/* clear info */
for (i = 0; i < 75; i++) {
s_buf_queue_overview[i] = ' ';
}
/* set pending task name */
for (task_listnode = buf_queue->blk_obj.blk_list.next;
task_listnode != &buf_queue->blk_obj.blk_list;
task_listnode = task_listnode->next) {
task = krhino_list_entry(task_listnode, ktask_t, task_list);
task_name = task->task_name == NULL ? "anonym" : task->task_name;
for (i = 0; i < 20; i++) {
s_buf_queue_overview[55 + i] = ' ';
}
for (i = 0; (i < 20) && (i < strlen(task_name)); i++) {
s_buf_queue_overview[55 + i] = task_name[i];
}
/* print */
print_func(s_buf_queue_overview);
}
}
}
#else
void debug_buf_queue_overview(int (*print_func)(const char *fmt, ...))
{
print_func("RHINO_CONFIG_KOBJ_LIST in k_config.h is closed!\r\n");
}
#endif
#endif
#if (RHINO_CONFIG_QUEUE > 0)
#if (RHINO_CONFIG_KOBJ_LIST > 0)
void debug_queue_overview(int (*print_func)(const char *fmt, ...))
{
int i;
klist_t *listnode, *task_listnode;
ktask_t *task;
kqueue_t *queue;
const name_t *task_name;
char s_queue_overview[] =
"0x 0x 0x 0x \r\n";
print_func("-------------------------------------------------------\r\n");
print_func("QueAddr TotalSize PeakNum CurrNum TaskWaiting\r\n");
print_func("-------------------------------------------------------\r\n");
for (listnode = g_kobj_list.queue_head.next;
listnode != &g_kobj_list.queue_head; listnode = listnode->next) {
queue = krhino_list_entry(listnode, kqueue_t, queue_item);
if (queue->blk_obj.obj_type != RHINO_QUEUE_OBJ_TYPE) {
print_func("Queue Type error!\r\n");
break;
}
/* set queue information */
k_int2str((int)queue->msg_q.queue_start, &s_queue_overview[2]);
k_int2str((int)queue->msg_q.size, &s_queue_overview[13]);
k_int2str((int)queue->msg_q.peak_num, &s_queue_overview[24]);
k_int2str((int)queue->msg_q.cur_num, &s_queue_overview[35]);
/* print */
print_func(s_queue_overview);
/* clear info */
for (i = 0; i < 64; i++) {
s_queue_overview[i] = ' ';
}
/* set pending task name */
for (task_listnode = queue->blk_obj.blk_list.next;
task_listnode != &queue->blk_obj.blk_list;
task_listnode = task_listnode->next) {
task = krhino_list_entry(task_listnode, ktask_t, task_list);
task_name = task->task_name == NULL ? "anonym" : task->task_name;
for (i = 0; i < 20; i++) {
s_queue_overview[44 + i] = ' ';
}
for (i = 0; (i < 20) && (i < strlen(task_name)); i++) {
s_queue_overview[44 + i] = task_name[i];
}
/* print */
print_func(s_queue_overview);
}
}
}
#else
void debug_queue_overview(int (*print_func)(const char *fmt, ...))
{
print_func("RHINO_CONFIG_KOBJ_LIST in k_config.h is closed!\r\n");
}
#endif
#endif
#if (RHINO_CONFIG_SEM > 0)
#if (RHINO_CONFIG_KOBJ_LIST > 0)
void debug_sem_overview(int (*print_func)(const char *fmt, ...))
{
int i, cnt = 0;
ksem_t *sem;
ktask_t *task;
klist_t *listnode, *task_listnode;
const name_t *task_name;
char s_sem_overview[] =
"0x 0x 0x \r\n";
char s_sem_total[] =
"Total: 0x \r\n";
print_func("--------------------------------------------\r\n");
print_func("SemAddr Count PeakCount TaskWaiting\r\n");
print_func("--------------------------------------------\r\n");
for (listnode = g_kobj_list.sem_head.next;
listnode != &g_kobj_list.sem_head; listnode = listnode->next) {
cnt++;
sem = krhino_list_entry(listnode, ksem_t, sem_item);
if (sem->blk_obj.obj_type != RHINO_SEM_OBJ_TYPE) {
print_func("Sem Type error sem addr %p!\r\n", sem);
break;
}
/* only show sem waited by task */
task_listnode = sem->blk_obj.blk_list.next;
if (task_listnode == &sem->blk_obj.blk_list) {
continue;
}
/* set sem information */
k_int2str((int)sem, &s_sem_overview[2]);
k_int2str((int)sem->count, &s_sem_overview[13]);
k_int2str((int)sem->peak_count, &s_sem_overview[24]);
/* print */
print_func(s_sem_overview);
/* clear info */
for (i = 0; i < 53; i++) {
s_sem_overview[i] = ' ';
}
/* set pending task name */
for (task_listnode = sem->blk_obj.blk_list.next;
task_listnode != &sem->blk_obj.blk_list;
task_listnode = task_listnode->next) {
task = krhino_list_entry(task_listnode, ktask_t, task_list);
task_name = task->task_name == NULL ? "anonym" : task->task_name;
for (i = 0; i < 20; i++) {
s_sem_overview[33 + i] = ' ';
}
for (i = 0; (i < 20) && (i < strlen(task_name)); i++) {
s_sem_overview[33 + i] = task_name[i];
}
/* print */
print_func(s_sem_overview);
}
}
k_int2str(cnt, &s_sem_total[9]);
print_func(s_sem_total);
}
#else
void debug_sem_overview(int (*print_func)(const char *fmt, ...))
{
print_func("RHINO_CONFIG_KOBJ_LIST in k_config.h is closed!\r\n");
}
#endif
#endif /* RHINO_CONFIG_SEM */
#if (RHINO_CONFIG_KOBJ_LIST > 0)
void debug_mutex_overview(int (*print_func)(const char *fmt, ...))
{
int i, cnt = 0;
kmutex_t *mutex;
ktask_t *task;
klist_t *listnode, *task_listnode;
const name_t *task_name;
char s_mutex_overview[] =
"0x 0x \r\n";
char s_mutex_total[] =
"Total: 0x \r\n";
print_func("--------------------------------------------\r\n");
print_func("MutexAddr TaskOwner NestCnt TaskWaiting\r\n");
print_func("--------------------------------------------\r\n");
for (listnode = g_kobj_list.mutex_head.next;
listnode != &g_kobj_list.mutex_head; listnode = listnode->next) {
cnt++;
mutex = krhino_list_entry(listnode, kmutex_t, mutex_item);
if (mutex->blk_obj.obj_type != RHINO_MUTEX_OBJ_TYPE) {
print_func("Mutex Type error!\r\n");
break;
}
/* only show mutex waited by task */
task = mutex->mutex_task;
if (task == NULL) {
continue;
}
/* set mutex information */
k_int2str((int)mutex, &s_mutex_overview[2]);
k_int2str((int)mutex->owner_nested, &s_mutex_overview[34]);
/* set owner task name */
task_name = task->task_name == NULL ? "anonym" : task->task_name;
for (i = 0; i < 20; i++) {
s_mutex_overview[11 + i] = ' ';
}
for (i = 0; i < strlen(task_name); i++) {
s_mutex_overview[11 + i] = task_name[i];
}
/* print */
print_func(s_mutex_overview);
/* clear info */
for (i = 0; i < 63; i++) {
s_mutex_overview[i] = ' ';
}
/* set pending task name */
for (task_listnode = mutex->blk_obj.blk_list.next;
task_listnode != &mutex->blk_obj.blk_list;
task_listnode = task_listnode->next) {
task = krhino_list_entry(task_listnode, ktask_t, task_list);
task_name = task->task_name == NULL ? "anonym" : task->task_name;
for (i = 0; i < 20; i++) {
s_mutex_overview[43 + i] = ' ';
}
for (i = 0; (i < 20) && (i < strlen(task_name)); i++) {
s_mutex_overview[43 + i] = task_name[i];
}
/* print */
print_func(s_mutex_overview);
}
}
k_int2str(cnt, &s_mutex_total[9]);
print_func(s_mutex_total);
}
#else
void debug_mutex_overview(int (*print_func)(const char *fmt, ...))
{
print_func("RHINO_CONFIG_KOBJ_LIST in k_config.h is closed!\r\n");
}
#endif
void debug_overview(int (*print_func)(const char *fmt, ...))
{
#if (RHINO_CONFIG_MM_TLF > 0)
print_func("========== Heap Info ==========\r\n");
debug_mm_overview(print_func);
#endif
print_func("========== Task Info ==========\r\n");
debug_task_overview(print_func);
#if (RHINO_CONFIG_QUEUE > 0)
print_func("========== Queue Info ==========\r\n");
debug_queue_overview(print_func);
#endif
#if (RHINO_CONFIG_BUF_QUEUE > 0)
print_func("======== Buf Queue Info ========\r\n");
debug_buf_queue_overview(print_func);
#endif
#if (RHINO_CONFIG_SEM > 0)
print_func("========== Sem Waiting ==========\r\n");
debug_sem_overview(print_func);
#endif
print_func("========= Mutex Waiting =========\r\n");
debug_mutex_overview(print_func);
}
#if (K_MM_STATISTIC > 0)
#if (RHINO_CONFIG_MM_TLF > 0)
void debug_heap_info_get(debug_mm_info_t *mm_info)
{
mm_info->total_size = g_kmm_head->free_size + g_kmm_head->used_size;
mm_info->free_size = g_kmm_head->free_size;
mm_info->used_size = g_kmm_head->used_size;
mm_info->maxused_size = g_kmm_head->maxused_size;
mm_info->maxblk_size = -1; /* not support current, will be replaced by krhino_mm_max_free_size_get() */
return;
}
#endif
#if (RHINO_CONFIG_MM_BLK > 0)
void debug_pool_info_get(debug_mm_info_t *mm_info)
{
mblk_info_t pool_info;
(void)krhino_mblk_info_nolock((mblk_pool_t *)g_kmm_head->fix_pool, &pool_info);
mm_info->total_size = pool_info.pool_size;
mm_info->free_size = pool_info.pool_size - pool_info.used_size;
mm_info->used_size = pool_info.used_size;
mm_info->maxused_size = pool_info.max_used_size;
mm_info->maxblk_size = pool_info.max_blk_size;
return;
}
#endif
#endif
| YifuLiu/AliOS-Things | components/debug/src/debug_overview.c | C | apache-2.0 | 18,017 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef DEBUG_OVERVIEW_H
#define DEBUG_OVERVIEW_H
#ifdef __cplusplus
extern "C" {
#endif
#define DEBUG_PANIC_IN_USER 1
#define DEBUG_PANIC_IN_KERNEL 0
typedef struct {
int32_t total_size;
int32_t free_size;
int32_t used_size;
int32_t maxused_size;
int32_t maxblk_size;
} debug_mm_info_t;
/**
* convert int to ascii(HEX)
* while using format % in libc, malloc/free is involved.
* this function avoid using malloc/free. so it works when heap corrupt.
* @param[in] num number
* @param[in] str fix 8 character str
* @return str
*/
char *k_int2str(int num, char *str);
/**
* This function print the overview of heap
* @param[in] print_func function to output information, NULL for
* "printf"
*/
void debug_mm_overview(int (*print_func)(const char *fmt, ...));
/**
* This function print the overview of tasks
* @param[in] print_func function to output information, NULL for
* "printf"
*/
void debug_task_overview(int (*print_func)(const char *fmt, ...));
/**
* This function print the overview of buf_queues
* @param[in] print_func function to output information, NULL for
* "printf"
*/
void debug_buf_queue_overview(int (*print_func)(const char *fmt, ...));
/**
* This function print the overview of queues
* @param[in] print_func function to output information, NULL for
* "printf"
*/
void debug_queue_overview(int (*print_func)(const char *fmt, ...));
/**
* This function print the overview of sems
* @param[in] print_func function to output information, NULL for
* "printf"
*/
void debug_sem_overview(int (*print_func)(const char *fmt, ...));
/**
* This function print the overview of mutex
* @param[in] print_func function to output information, NULL for
* "printf"
*/
void debug_mutex_overview(int (*print_func)(const char *fmt, ...));
/**
* This function print the overview of all
* @param[in] print_func function to output information, NULL for
* "printf"
*/
void debug_overview(int (*print_func)(const char *fmt, ...));
void debug_heap_info_get(debug_mm_info_t *mm_info);
void debug_pool_info_get(debug_mm_info_t *mm_info);
#ifdef __cplusplus
}
#endif
#endif /* DEBUG_OVERVIEW_H */
| YifuLiu/AliOS-Things | components/debug/src/debug_overview.h | C | apache-2.0 | 2,283 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdarg.h>
#include <stdbool.h>
#include <time.h>
#include "debug_api.h"
#include "k_compiler.h"
#include "aos/kernel.h"
#include "aos/debug.h"
#include "aos/errno.h"
int backtrace_now(int (*print_func)(const char *fmt, ...));
void debug_panic_backtrace(char *PC, int *SP, char *LR,
int (*print_func)(const char *fmt, ...));
#if AOS_COMP_CLI
#include "aos/cli.h"
#endif
#ifdef AOS_COMP_KV
#include "aos/kv.h"
#endif
/* reboot reason*/
#define DEFAULT_REBOOT_REASON DEBUG_REBOOT_REASON_REPOWER
#define SYS_REBOOT_REASON "reboot reason"
#ifndef panic_print
#define panic_print printk
#endif
#define panic_print_direct printk_direct
#if (RHINO_CONFIG_CPU_NUM > 1)
kspinlock_t g_panic_print_lock = {KRHINO_SPINLOCK_FREE_VAL, 0, 0};
#endif
#if DEBUG_ULOG_FLUSH
extern void uring_fifo_flush(void);
void debug_log_flush(void)
{
uring_fifo_flush();
}
#endif
/* use cli in panic depends on mcu*/
__attribute__((weak)) void alios_cli_panic_hook()
{
return;
}
extern void hal_reboot(void);
/* functions followed should defined by arch\...\panic_c.c */
extern void panicShowRegs(void *context,
int (*print_func)(const char *fmt, ...));
extern void panicGetCtx(void *context, char **pPC, char **pLR, int **pSP);
/* functions followed should defined by arch\...\backtrace.c */
extern int backtrace_caller(char *PC, int *SP,
int (*print_func)(const char *fmt, ...));
extern int backtrace_callee(char *PC, int *SP, char *LR,
int (*print_func)(const char *fmt, ...));
/* how many steps has finished when crash */
#define DEBUG_PANIC_STEP_MAX 32
volatile uint32_t g_crash_steps = 0;
volatile uint32_t g_crash_by_NMI = 0;
volatile uint32_t g_crash_not_reboot = 0;
void debug_cpu_stop(void)
{
#if (RHINO_CONFIG_CPU_NUM > 1)
cpu_freeze_others();
#endif
krhino_sched_disable();
}
void debug_cpu_goto_cli(void)
{
g_crash_not_reboot = OS_PANIC_NOT_REBOOT;
}
uint32_t debug_cpu_in_crash(void)
{
return g_crash_steps;
}
void panicNmiFlagSet()
{
g_crash_by_NMI = OS_PANIC_BY_NMI;
}
int panicNmiFlagCheck()
{
return (g_crash_by_NMI == OS_PANIC_BY_NMI);
}
static void panic_goto_cli(void)
{
cpu_intrpt_save();
extern uint8_t g_sched_lock[];
if (0 == g_sched_lock[cpu_cur_get()]) {
g_sched_lock[cpu_cur_get()]++;
}
extern int32_t g_cli_direct_read;
g_cli_direct_read = 1;
alios_cli_panic_hook();
#if AOS_COMP_CLI
extern void cli_main_panic(void);
cli_main_panic();
#endif
while (1);
}
/* should exeception be restored?
reture 1 YES, 0 NO*/
int panicRestoreCheck(void)
{
return 0;
}
static void debug_panic_end(void)
{
#if !DEBUG_PANIC_CLI
if (g_crash_not_reboot == OS_PANIC_NOT_REBOOT) {
panic_goto_cli();
} else if (panicNmiFlagCheck() == 0) {
hal_reboot();
} else { /* '$' is also effective in release version*/
panic_goto_cli();
}
#else /* debug version*/
panic_goto_cli();
#endif
}
void stack_dump(cpu_stack_t *stack, uint32_t size)
{
uint32_t zero_cnt, zero_prt, idx;
for (idx = 0, zero_cnt = 0, zero_prt = 0; idx < size; idx += 4) {
if (stack[idx] == 0 && stack[idx + 1] == 0
&& stack[idx + 2] == 0 && stack[idx + 3] == 0) {
zero_cnt++;
if (zero_cnt == 1) {
panic_print(".........................( All Zeros ).........................\r\n");
zero_prt = 1;
continue;
}
if (zero_prt == 1) {
continue;
}
}
panic_print("(0x%08X): 0x%08X 0x%08X 0x%08X 0x%08X\r\n",
&stack[idx],
(void *)stack[idx], (void *)stack[idx + 1], (void *)stack[idx + 2], (void *)stack[idx + 3]);
zero_cnt = 0;
zero_prt = 0;
}
}
void debug_cur_task_stack_dump(void)
{
cpu_stack_t *stack;
uint32_t stack_size;
ktask_t *task = g_active_task[cpu_cur_get()];
stack = task->task_stack_base;
stack_size = task->stack_size;
if (stack != NULL) {
panic_print("========== Stack info ==========\r\n");
stack_dump(stack, stack_size);
}
}
void debug_cur_task_show(void)
{
ktask_t *task;
uint8_t time_buffer[30];
long long ms = aos_calendar_localtime_get();
time_t rawtime = ms / 1000;
struct tm *tm = localtime(&rawtime);
memset(time_buffer, 0, sizeof(time_buffer));
if (tm) {
strftime((char *)time_buffer, sizeof(time_buffer), "%F %H:%M:%S", tm);
panic_print("crash time : %s\r\n", time_buffer);
}
/* output crash task's name */
task = g_active_task[cpu_cur_get()];
if (task->task_name != NULL) {
panic_print("current task : %s\r\n", task->task_name);
} else {
panic_print("cur task name is NULL\r\n");
}
}
#if RHINO_CONFIG_MM_DEBUG
static void debug_print_block(k_mm_list_t *b, int (*print_func)(const char *fmt, ...))
{
if (!b) {
return;
}
if (print_func == NULL) {
print_func = panic_print_direct;
}
print_func("0x%08x ", (uintptr_t)b);
if (b->buf_size & MM_BUFF_FREE) {
if (b->dye != MM_DYE_FREE) {
print_func("!");
} else {
print_func(" ");
}
print_func("free ");
} else {
if (b->dye != MM_DYE_USED) {
print_func("!");
} else {
print_func(" ");
}
print_func("used ");
}
if (MM_GET_BUF_SIZE(b)) {
print_func(" %6lu ", (unsigned long)MM_GET_BUF_SIZE(b));
} else {
print_func(" sentinel ");
}
if (b->buf_size & MM_BUFF_FREE) {
if (b->dye != MM_DYE_FREE) {
print_func(" %8x ", b->dye);
} else {
print_func(" OK ");
}
} else {
if (b->dye != MM_DYE_USED) {
print_func(" %8x ", b->dye);
} else {
print_func(" OK ");
}
}
print_func(" 0x%-8x ", b->owner);
#if (RHINO_CONFIG_MM_TRACE_LVL > 0)
/* If double free, print last alloc trace maybe useful.
This info is not useful if this mem alloc-and-freed by another module between.
*/
//if ((b->buf_size & MM_BUFF_FREE) == 0)
{
int idx;
print_func(" (%p", b->trace[0]);
for (idx = 1 ; idx < RHINO_CONFIG_MM_TRACE_LVL ; idx++) {
print_func(" <- %p", b->trace[idx]);
}
print_func(")");
}
#endif
print_func("\r\n");
}
static bool debug_blk_damaged(k_mm_list_t *mm_list)
{
if (!mm_list) {
return false;
}
if (mm_list->dye != MM_DYE_USED && mm_list->dye != MM_DYE_FREE) {
return true;
}
if (mm_list->buf_size & MM_BUFF_FREE) {
if (mm_list->dye != MM_DYE_FREE) {
return true;
}
} else {
if (mm_list->dye != MM_DYE_USED) {
return true;
}
}
/* detect bufsize skip lastblk */
if (mm_list->owner != MM_LAST_BLK_MAGIC) {
k_mm_list_t *next_b = MM_GET_NEXT_BLK(mm_list);
if (next_b->dye != MM_DYE_USED && next_b->dye != MM_DYE_FREE) {
return true;
}
}
return false;
}
void debug_dump_mm_error(k_mm_head *mmhead, int (*print_func)(const char *fmt, ...))
{
k_mm_region_info_t *reginfo, *nextreg;
k_mm_list_t *next, *cur, *prev, *pprev;
if (!mmhead) {
return;
}
if (print_func == NULL) {
print_func = panic_print_direct;
}
print_func("ALL BLOCKS\r\n");
print_func("Blk_Addr Stat Len Chk Caller Point\r\n");
reginfo = mmhead->regioninfo;
prev = NULL;
pprev = NULL;
while (reginfo) {
cur = MM_GET_THIS_BLK(reginfo);
while (cur) {
if (debug_blk_damaged(cur)) {
debug_print_block(pprev, print_func);
debug_print_block(prev, print_func);
debug_print_block(cur, print_func);
}
if (MM_GET_BUF_SIZE(cur)) {
next = MM_GET_NEXT_BLK(cur);
} else {
next = NULL;
}
pprev = prev;
prev = cur;
cur = next;
}
nextreg = reginfo->next;
reginfo = nextreg;
}
}
void dump_mm_all_error_block(void *pmm_head, int (*print_func)(const char *fmt, ...))
{
if (print_func == NULL) {
print_func = panic_print_direct;
}
print_func("g_kmm_head = %8x\r\n", (unsigned int)pmm_head);
/* kernel and user space use the same mm head file */
debug_dump_mm_error(pmm_head, print_func);
}
void dump_mm_sys_error_info(int (*print_func)(const char *fmt, ...))
{
void *pmm_head = g_kmm_head;
print_func("kernel space mem layout:\r\n");
dump_mm_all_error_block(pmm_head, print_func);
}
#endif /* RHINO_CONFIG_MM_DEBUG */
void fiqafterpanicHandler(void *context)
{
static int *SP = NULL;
static char *PC = NULL;
static char *LR = NULL;
#if (RHINO_CONFIG_CPU_NUM > 1)
krhino_spin_lock(&g_panic_print_lock);
#endif
panic_print("\r\n!!!!!!!!!! core %d Enter fiq !!!!!!!!!!\r\n", cpu_cur_get());
if (context != NULL) {
panicGetCtx(context, &PC, &LR, &SP);
}
panicShowRegs(context, panic_print);
debug_panic_backtrace(PC, SP, LR, panic_print);
#if (RHINO_CONFIG_CPU_NUM > 1)
krhino_spin_unlock(&g_panic_print_lock);
#endif
return;
}
/* fault/exception entry
notice: this function maybe reentried by double exception
first exception, input context
second exception, input NULL */
void panicHandler(void *context)
{
static int *SP = NULL;
static char *PC = NULL;
static char *LR = NULL;
kstat_t stat_save;
#if RHINO_CONFIG_MM_DEBUG
g_mmlk_cnt = 0;
#endif
#if (RHINO_CONFIG_CPU_NUM > 1)
krhino_spin_lock(&g_panic_print_lock);
#endif
stat_save = g_sys_stat;
g_sys_stat = RHINO_STOPPED;
/* g_crash_steps++ before panicHandler */
if (g_crash_steps > 1 && g_crash_steps < DEBUG_PANIC_STEP_MAX) {
panic_print("......\r\n");
}
switch (g_crash_steps) {
case 1:
if (panicNmiFlagCheck()) { /*for $#@! feature*/
panic_print("\r\n!!!!!!!! Stopped by '$#@!' !!!!!!!!\r\n");
}
panic_print("\r\n!!!!!!!!!! Exception !!!!!!!!!!\r\n");
debug_cur_task_show();
if (context != NULL) {
panicGetCtx(context, &PC, &LR, &SP);
}
panicShowRegs(context, panic_print);
g_crash_steps++;
case 2:
panic_print("========== Call stack ==========\r\n");
debug_panic_backtrace(PC, SP, LR, panic_print);
g_crash_steps++;
case 3:
#if (RHINO_CONFIG_MM_TLF > 0)
panic_print("========== Heap Info ==========\r\n");
debug_mm_overview(panic_print);
#endif
g_crash_steps++;
case 4:
panic_print("========== Task Info ==========\r\n");
debug_task_overview(panic_print);
g_crash_steps++;
case 5:
#if (RHINO_CONFIG_QUEUE > 0)
panic_print("========== Queue Info ==========\r\n");
debug_queue_overview(panic_print);
#endif
g_crash_steps++;
case 6:
#if (RHINO_CONFIG_BUF_QUEUE > 0)
panic_print("======== Buf Queue Info ========\r\n");
debug_buf_queue_overview(panic_print);
#endif
g_crash_steps++;
case 7:
#if (RHINO_CONFIG_SEM > 0)
panic_print("========= Sem Waiting ==========\r\n");
debug_sem_overview(panic_print);
#endif
g_crash_steps++;
case 8:
panic_print("======== Mutex Waiting =========\r\n");
debug_mutex_overview(panic_print);
g_crash_steps++;
case 9:
#if RHINO_CONFIG_MM_DEBUG
panic_print("======== all memory error blocks =========\r\n");
dump_mm_sys_error_info(panic_print);
#endif
g_crash_steps++;
case 10:
if (SP != NULL) {
debug_cur_task_stack_dump();
}
g_crash_steps++;
case 11:
panic_print("!!!!!!!!!! dump end !!!!!!!!!!\r\n");
g_crash_steps++;
default:
break;
}
g_crash_steps = DEBUG_PANIC_STEP_MAX;
#if (RHINO_CONFIG_CPU_NUM > 1)
krhino_spin_unlock(&g_panic_print_lock);
#endif
#if DEBUG_LAST_WORD_ENABLE
debug_reboot_reason_update(DEBUG_REBOOT_REASON_PANIC);
#endif
#if DEBUG_ULOG_FLUSH
debug_log_flush();
#endif
debug_panic_end();
g_sys_stat = stat_save;
g_crash_steps = 0;
g_crash_by_NMI = 0;
}
void debug_fatal_error(kstat_t err, char *file, int line)
{
void *pmm_head = NULL;
(void)pmm_head;
#if (RHINO_CONFIG_CPU_NUM > 1)
cpu_freeze_others();
#endif
krhino_sched_disable();
g_crash_steps = 1;
panic_print("!!!!!!!!!! Fatal Error !!!!!!!!!!\r\n");
if (err == RHINO_TASK_STACK_OVF) {
panic_print("Task : %s Stack Overflow!\r\n", g_active_task[cpu_cur_get()]->task_name);
}
debug_cur_task_show();
#if (RHINO_CONFIG_MM_TLF > 0)
panic_print("========== Heap Info ==========\r\n");
debug_mm_overview(panic_print);
#endif
panic_print("========== Task Info ==========\r\n");
debug_task_overview(panic_print);
//debug_backtrace_now();
backtrace_now(panic_print);
#if RHINO_CONFIG_MM_DEBUG
panic_print("======== all memory error blocks =========\r\n");
dump_mm_sys_error_info(panic_print);
#endif
debug_cur_task_stack_dump();
panic_print("!!!!!!!!!! dump end !!!!!!!!!!\r\n");
#if DEBUG_LAST_WORD_ENABLE
debug_reboot_reason_update(DEBUG_REBOOT_REASON_FATAL_ERR);
#endif
#if DEBUG_ULOG_FLUSH
debug_log_flush();
#endif
debug_panic_end();
g_crash_steps = 0;
}
void debug_init(void)
{
#if AOS_COMP_CLI
debug_cli_cmd_init();
#endif
#if DEBUG_LAST_WORD_ENABLE
debug_lastword_init();
#endif
}
| YifuLiu/AliOS-Things | components/debug/src/debug_panic.c | C | apache-2.0 | 14,103 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef DEBUG_PANIC_H
#define DEBUG_PANIC_H
#ifdef __cplusplus
extern "C" {
#endif
#define DEBUG_PANIC_STEP_MAX 32
#define OS_PANIC_BY_NMI 0x31415926
#define OS_PANIC_NOT_REBOOT 0x21314916
/* how many steps has finished when crash */
extern volatile uint32_t g_crash_steps;
/* crash status */
extern volatile uint32_t g_crash_by_NMI;
extern volatile uint32_t g_crash_not_reboot;
/* fault/exception entry
* notice: this function maybe reentried by double exception
*/
void panicHandler(void *context);
void panicNmiFlagSet();
int panicNmiFlagCheck();
void debug_init(void);
void debug_cpu_stop(void);
uint32_t debug_cpu_in_crash(void);
void fiqafterpanicHandler(void *context);
void debug_fatal_error(kstat_t err, char *file, int line);
#ifdef __cplusplus
}
#endif
#endif /* DEBUG_PANIC_H */
| YifuLiu/AliOS-Things | components/debug/src/debug_panic.h | C | apache-2.0 | 871 |
#include <stdarg.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include "aos/debug.h"
#include "debug_api.h"
#define LONGFLAG 0x00000001
#define LONGLONGFLAG 0x00000002
#define HALFFLAG 0x00000004
#define HALFHALFFLAG 0x00000008
#define SIZETFLAG 0x00000010
#define INTMAXFLAG 0x00000020
#define PTRDIFFFLAG 0x00000040
#define ALTFLAG 0x00000080
#define CAPSFLAG 0x00000100
#define SHOWSIGNFLAG 0x00000200
#define SIGNEDFLAG 0x00000400
#define LEFTFORMATFLAG 0x00000800
#define LEADZEROFLAG 0x00001000
#define BLANKPOSFLAG 0x00002000
extern volatile uint32_t g_crash_steps;
union all_format_type {
unsigned int i[2];
long long ll;
double d;
} format_var;
/* alios_debug_print depends on mcu*/
__attribute__((weak)) int alios_debug_print(const char *buf, int size)
{
return 0;
}
#define OUTPUT_BUF(val, mode, buf) \
do { \
if (buf) { \
if (mode == 1) { \
format_var.ll = val; \
buf[index++] = format_var.i[0]; \
} else if(mode == 2) { \
format_var.ll = val; \
buf[index++] = format_var.i[0]; \
buf[index++] = format_var.i[1]; \
} else if(mode == 3) { \
format_var.d = val; \
buf[index++] = format_var.i[0]; \
buf[index++] = format_var.i[1]; \
} \
} } while(0)
#define OUTPUT_STRING(str, len)\
do { \
if (!buf) { \
err = alios_debug_print(str, len); \
if (err < 0) { \
goto exit; \
} else { \
chars_written += err; \
} \
} } while(0)
#define OUTPUT_CHAR(c) \
do { \
char __temp[1] = { c }; \
OUTPUT_STRING(__temp, 1); \
} while (0)
static const char hextable[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
static const char hextable_caps[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
static char *longlong_to_string(char *buf,
unsigned long long n,
size_t len,
unsigned int flag,
char *signchar)
{
size_t pos = len;
int negative = 0;
if ((flag & SIGNEDFLAG) && (long long)n < 0) {
negative = 1;
n = -n;
}
buf[--pos] = 0;
/* only do the math if the number is >= 10 */
union {
unsigned int ui[2];
unsigned long long ull;
} union_ull;
union_ull.ull = n;
int digit;
if (union_ull.ui[0] == 0) {
buf[--pos] = '0';
} else {
while (union_ull.ui[0] > 0) {
digit = union_ull.ui[0] % 10;
union_ull.ui[0] /= 10;
buf[--pos] = digit + '0';
}
}
while (union_ull.ui[1] > 0) {
digit = union_ull.ui[1] % 10;
union_ull.ui[1] /= 10;
buf[--pos] = digit + '0';
}
if (negative) {
*signchar = '-';
} else if ((flag & SHOWSIGNFLAG)) {
*signchar = '+';
} else if ((flag & BLANKPOSFLAG)) {
*signchar = ' ';
} else {
*signchar = '\0';
}
return &buf[pos];
}
static char *longlong_to_hexstring(char *buf,
unsigned long long u,
size_t len,
unsigned int flag)
{
size_t pos = len;
const char *table = (flag & CAPSFLAG) ? hextable_caps : hextable;
buf[--pos] = 0;
do {
unsigned int digit = u % 16;
u /= 16;
buf[--pos] = table[digit];
} while (u != 0);
return &buf[pos];
}
union double_int {
double d;
uint64_t i;
};
#define OUT(c) buf[pos++] = (c)
#define OUTSTR(str) do { for (size_t i = 0; (str)[i] != 0; i++) OUT((str)[i]); } while (0)
/* print up to a 4 digit exponent as string, with sign */
static size_t exponent_to_string(char *buf, int32_t exponent)
{
size_t pos = 0;
/* handle sign */
if (exponent < 0) {
OUT('-');
exponent = -exponent;
} else {
OUT('+');
}
/* see how far we need to bump into the string to print from the right */
if (exponent >= 1000) {
pos += 4;
} else if (exponent >= 100) {
pos += 3;
} else if (exponent >= 10) {
pos += 2;
} else {
pos++;
}
/* print decimal string, from the right */
uint32_t i = pos;
do {
uint32_t digit = (uint32_t)exponent % 10;
buf[--i] = digit + '0';
exponent /= 10;
} while (exponent != 0);
/* return number of characters printed */
return pos;
}
static char *double_to_string(char *buf, size_t len, double d, uint32_t flag)
{
size_t pos = 0;
union double_int u = { d };
uint32_t exponent = (u.i >> 52) & 0x7ff;
uint64_t fraction = (u.i & ((1ULL << 52) - 1));
uint8_t neg = !!(u.i & (1ULL << 63));
/* start constructing the string */
if (neg) {
OUT('-');
d = -d;
}
/* look for special cases */
if (exponent == 0x7ff) {
if (fraction == 0) {
/* infinity */
if (flag & CAPSFLAG) {
OUTSTR("INF");
} else {
OUTSTR("inf");
}
} else {
/* NaN */
if (flag & CAPSFLAG) {
OUTSTR("NAN");
} else {
OUTSTR("nan");
}
}
} else if (exponent == 0) {
if (fraction == 0) {
/* zero */
OUTSTR("0.000000");
} else {
/* denormalized */
/* XXX does not handle */
if (flag & CAPSFLAG) {
OUTSTR("DEN");
} else {
OUTSTR("den");
}
}
} else {
/* see if it's in the range of floats we can easily print */
int exponent_signed = exponent - 1023;
if (exponent_signed < -52 || exponent_signed > 52) {
OUTSTR("<range>");
} else {
/* start by walking backwards through the string */
#define OUTREV(c) do { if (&buf[pos] == buf) goto done; else buf[--pos] = (c); } while (0)
pos = len;
OUTREV(0);
/* reserve space for the fractional component first */
for (int i = 0; i <= 6; i++) {
OUTREV('0');
}
size_t decimal_spot = pos;
/* print the integer portion */
uint64_t u;
if (exponent_signed >= 0) {
u = fraction;
u |= (1ULL << 52);
u >>= (52 - exponent_signed);
char *s = longlong_to_string(buf, u, pos + 1, flag, &(char) {
0
});
pos = s - buf;
} else {
/* exponent is negative */
u = 0;
OUTREV('0');
}
buf[decimal_spot] = '.';
/* handle the fractional part */
uint32_t frac = ((d - u) * 1000000) + .5;
uint32_t i = decimal_spot + 6 + 1;
while (frac != 0) {
uint32_t digit = frac % 10;
buf[--i] = digit + '0';
frac /= 10;
}
if (neg) {
OUTREV('-');
}
done:
/* separate return path, since we've been walking backwards through the string */
return &buf[pos];
}
#undef OUTREV
}
buf[pos] = 0;
return buf;
}
static char *double_to_hexstring(char *buf, size_t len, double d, uint32_t flag)
{
size_t pos = 0;
union double_int u = { d };
uint32_t exponent = (u.i >> 52) & 0x7ff;
uint64_t fraction = (u.i & ((1ULL << 52) - 1));
uint8_t neg = !!(u.i & (1ULL << 63));
/* start constructing the string */
if (neg) {
OUT('-');
}
/* look for special cases */
if (exponent == 0x7ff) {
if (fraction == 0) {
/* infinity */
if (flag & CAPSFLAG) {
OUTSTR("INF");
} else {
OUTSTR("inf");
}
} else {
/* NaN */
if (flag & CAPSFLAG) {
OUTSTR("NAN");
} else {
OUTSTR("nan");
}
}
} else if (exponent == 0) {
if (fraction == 0) {
/* zero */
if (flag & CAPSFLAG) {
OUTSTR("0X0P+0");
} else {
OUTSTR("0x0p+0");
}
} else {
/* denormalized */
/* XXX does not handle */
if (flag & CAPSFLAG) {
OUTSTR("DEN");
} else {
OUTSTR("den");
}
}
} else {
/* regular normalized numbers:
* 0x1p+1
* 0x1.0000000000001p+1
* 0X1.FFFFFFFFFFFFFP+1023
* 0x1.FFFFFFFFFFFFFP+1023
*/
int exponent_signed = exponent - 1023;
/* implicit 1. */
if (flag & CAPSFLAG) {
OUTSTR("0X1");
} else {
OUTSTR("0x1");
}
/* select the appropriate hex case table */
const char *table = (flag & CAPSFLAG) ? hextable_caps : hextable;
int zero_count = 0;
uint8_t output_dot = 0;
for (int i = 52 - 4; i >= 0; i -= 4) {
uint32_t digit = (fraction >> i) & 0xf;
if (digit == 0) {
zero_count++;
} else {
/* output a . the first time we output a char */
if (!output_dot) {
OUT('.');
output_dot = 1;
}
/* if we have a non zero digit, see if we need to output a string of zeros */
while (zero_count > 0) {
OUT('0');
zero_count--;
}
buf[pos++] = table[digit];
}
}
/* handle the exponent */
buf[pos++] = (flag & CAPSFLAG) ? 'P' : 'p';
pos += exponent_to_string(&buf[pos], exponent_signed);
}
buf[pos] = 0;
return buf;
}
#undef OUT
#undef OUTSTR
int print_driver(const char *fmt, va_list ap, unsigned int buf[])
{
int err = 0;
char c;
unsigned char uc;
const char *s;
size_t string_len;
unsigned long long n;
//void *ptr;
int flags;
unsigned int format_num;
char signchar;
size_t chars_written = 0;
char num_buffer[32];
int index = 0;
for (;;) {
/* reset the format state */
flags = 0;
format_num = 0;
signchar = '\0';
/* handle regular chars that aren't format related */
s = fmt;
string_len = 0;
while ((c = *fmt++) != 0) {
if (c == '%') {
break; /* we saw a '%', break and start parsing format */
}
string_len++;
}
/* output the string we've accumulated */
if (string_len > 0) {
OUTPUT_STRING(s, string_len);
}
/* make sure we haven't just hit the end of the string */
if (c == 0) {
break;
}
next_format:
/* grab the next format character */
c = *fmt++;
if (c == 0) {
break;
}
switch (c) {
case '0'...'9':
if (c == '0' && format_num == 0) {
flags |= LEADZEROFLAG;
}
format_num *= 10;
format_num += c - '0';
goto next_format;
case '.':
/* XXX for now eat numeric formatting */
goto next_format;
case '%':
OUTPUT_CHAR('%');
break;
case 'c':
uc = va_arg(ap, unsigned int);
OUTPUT_CHAR(uc);
OUTPUT_BUF(uc, 1, buf);
break;
case 's':
s = va_arg(ap, const char *);
OUTPUT_BUF((unsigned int)(uintptr_t)s, 1, buf);
if (s == 0) {
s = "<null>";
}
flags &= ~LEADZEROFLAG; /* doesn't make sense for strings */
goto _output_string;
case '-':
flags |= LEFTFORMATFLAG;
goto next_format;
case '+':
flags |= SHOWSIGNFLAG;
goto next_format;
case ' ':
flags |= BLANKPOSFLAG;
goto next_format;
case '#':
flags |= ALTFLAG;
goto next_format;
case 'l':
if (flags & LONGFLAG) {
flags |= LONGLONGFLAG;
}
flags |= LONGFLAG;
goto next_format;
case 'h':
if (flags & HALFFLAG) {
flags |= HALFHALFFLAG;
}
flags |= HALFFLAG;
goto next_format;
case 'z':
flags |= SIZETFLAG;
goto next_format;
case 'j':
flags |= INTMAXFLAG;
goto next_format;
case 't':
flags |= PTRDIFFFLAG;
goto next_format;
case 'i':
case 'd':
if (flags & LONGLONGFLAG) {
n = va_arg(ap, long long);
OUTPUT_BUF(n, 2, buf);
} else {
n = (flags & LONGFLAG) ? va_arg(ap, long) :
(flags & HALFHALFFLAG) ? (signed char)va_arg(ap, int) :
(flags & HALFFLAG) ? (short)va_arg(ap, int) :
(flags & SIZETFLAG) ? va_arg(ap, ssize_t) :
(flags & INTMAXFLAG) ? va_arg(ap, intmax_t) :
(flags & PTRDIFFFLAG) ? va_arg(ap, ptrdiff_t) :
va_arg(ap, int);
OUTPUT_BUF(n, 1, buf);
}
flags |= SIGNEDFLAG;
s = longlong_to_string(num_buffer, n, sizeof(num_buffer), flags, &signchar);
goto _output_string;
case 'u':
if (flags & LONGLONGFLAG) {
n = va_arg(ap, unsigned long long);
OUTPUT_BUF(n, 2, buf);
} else {
n = (flags & LONGFLAG) ? va_arg(ap, unsigned long) :
(flags & HALFHALFFLAG) ? (unsigned char)va_arg(ap, unsigned int) :
(flags & HALFFLAG) ? (unsigned short)va_arg(ap, unsigned int) :
(flags & SIZETFLAG) ? va_arg(ap, size_t) :
(flags & INTMAXFLAG) ? va_arg(ap, uintmax_t) :
(flags & PTRDIFFFLAG) ? (uintptr_t)va_arg(ap, ptrdiff_t) :
va_arg(ap, unsigned int);
OUTPUT_BUF(n, 1, buf);
}
s = longlong_to_string(num_buffer, n, sizeof(num_buffer), flags, &signchar);
goto _output_string;
case 'p':
flags |= LONGFLAG | ALTFLAG;
goto hex;
case 'X':
flags |= CAPSFLAG;
/* fallthrough */
hex:
case 'x':
if (flags & LONGLONGFLAG) {
n = va_arg(ap, unsigned long long);
OUTPUT_BUF(n, 2, buf);
} else {
n = (flags & LONGFLAG) ? va_arg(ap, unsigned long) :
(flags & HALFHALFFLAG) ? (unsigned char)va_arg(ap, unsigned int) :
(flags & HALFFLAG) ? (unsigned short)va_arg(ap, unsigned int) :
(flags & SIZETFLAG) ? va_arg(ap, size_t) :
(flags & INTMAXFLAG) ? va_arg(ap, uintmax_t) :
(flags & PTRDIFFFLAG) ? (uintptr_t)va_arg(ap, ptrdiff_t) :
va_arg(ap, unsigned int);
OUTPUT_BUF(n, 1, buf);
}
s = longlong_to_hexstring(num_buffer, n, sizeof(num_buffer), flags);
if (flags & ALTFLAG) {
OUTPUT_CHAR('0');
OUTPUT_CHAR((flags & CAPSFLAG) ? 'X' : 'x');
}
goto _output_string;
case 'n':
break;
case 'F':
flags |= CAPSFLAG;
/* fallthrough */
case 'f': {
double d = va_arg(ap, double);
OUTPUT_BUF(d, 3, buf);
s = double_to_string(num_buffer, sizeof(num_buffer), d, flags);
goto _output_string;
}
case 'A':
flags |= CAPSFLAG;
/* fallthrough */
case 'a': {
double d = va_arg(ap, double);
OUTPUT_BUF(d, 3, buf);
s = double_to_hexstring(num_buffer, sizeof(num_buffer), d, flags);
goto _output_string;
}
default:
OUTPUT_CHAR('%');
OUTPUT_CHAR(c);
break;
}
/* move on to the next field */
continue;
/* shared output code */
_output_string:
string_len = strlen(s);
if (flags & LEFTFORMATFLAG) {
/* left justify the text */
OUTPUT_STRING(s, string_len);
unsigned int written = err;
/* pad to the right (if necessary) */
for (; format_num > written; format_num--) {
OUTPUT_CHAR(' ');
}
} else {
/* right justify the text (digits) */
/* if we're going to print a sign digit,
* it'll chew up one byte of the format size */
if (signchar != '\0' && format_num > 0) {
format_num--;
}
/* output the sign char before the leading zeros */
if (flags & LEADZEROFLAG && signchar != '\0') {
OUTPUT_CHAR(signchar);
}
/* pad according to the format string */
for (; format_num > string_len; format_num--) {
OUTPUT_CHAR(flags & LEADZEROFLAG ? '0' : ' ');
}
/* if not leading zeros, output the sign char just before the number */
if (!(flags & LEADZEROFLAG) && signchar != '\0') {
OUTPUT_CHAR(signchar);
}
/* output the string */
OUTPUT_STRING(s, string_len);
}
continue;
}
//return index;
exit:
return (err < 0) ? err : index;
//return (err < 0) ? err : (int)chars_written;
}
#undef OUTPUT_STRING
#undef OUTPUT_CHAR
static int _vfprintf(const char *fmt, va_list ap)
{
return print_driver(fmt, ap, NULL);
}
int32_t aos_debug_printf(const char *fmt, ...)
{
int ret;
va_list ap;
#if DEBUG_LAST_WORD_ENABLE
if (g_crash_steps > 0) {
/* coredump log is both recorded in lastword region */
va_start(ap, fmt);
ret = vprint_str(fmt, ap);
va_end(ap);
}
#endif
va_start(ap, fmt);
ret = _vfprintf(fmt, ap);
va_end(ap);
return ret;
}
int printk_direct(const char *fmt, ...)
{
int ret;
va_list ap;
va_start(ap, fmt);
ret = _vfprintf(fmt, ap);
va_end(ap);
return ret;
}
| YifuLiu/AliOS-Things | components/debug/src/debug_print.c | C | apache-2.0 | 19,599 |
#ifndef __DEBUG_PRINT_H
#define __DEBUG_PRINT_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdarg.h>
int printk_direct(const char *fmt, ...);
/* for ulog encoder*/
int print_driver(const char *fmt, va_list ap, unsigned int buf[]);
#ifdef __cplusplus
}
#endif
#endif /* __DEBUG_PRINT_H */
| YifuLiu/AliOS-Things | components/debug/src/debug_print.h | C | apache-2.0 | 300 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#if AOS_COMP_CLI
#include <stdio.h>
#include <assert.h>
#include "debug_api.h"
#include "aos/debug.h"
#include "aos/cli.h"
#ifdef AOS_COMP_ULOG
#include "ulog/ulog.h"
#endif
#define MAX_32 ((long)(~0UL))
#define MAX_64 ((long long)(~0ULL))
typedef int (*print_func)(const char *fmt, ...);
static void print_test(int (*print_func)(const char *fmt, ...))
{
int a = 1234;
unsigned long long b = 12345678;
float c = 3.14;
double d = 5.6789;
print_func("int : %d max_32 : 0x%X\r\n", a, MAX_32);
print_func("ll : %lld max_64 : 0x%llX\r\n", b, MAX_64);
print_func("float : %f\r\n", c);
print_func("double : %lf\r\n", d);
}
/*test for printf when irq disable, which mostly test uart_send_dirver of vendor*/
static void print_test_cmd(int argc, char **argv)
{
CPSR_ALLOC();
printk("\r\nbegin test printk\r\n");
print_test(printk);
RHINO_CPU_INTRPT_DISABLE();
printk("printk : hello world ! yes we can\r\n");
RHINO_CPU_INTRPT_ENABLE();
printk("\r\nprintk test end\r\n");
printf("\r\nbegin test printf\r\n");
print_test(printf);
RHINO_CPU_INTRPT_DISABLE();
printf("printf : hello world ! yes we can\r\n");
RHINO_CPU_INTRPT_ENABLE();
printf("\r\nprintf test end\r\n");
}
ALIOS_CLI_CMD_REGISTER(print_test_cmd, print_t, Console Cmd Print Test)
/* test for ulog encoder to fs*/
#ifdef AOS_COMP_ULOG
static void ulog_encode_fs_test(int argc, char **argv)
{
static int cnt = 0;
LOGE("AOS", "hello alibaba : %d\n", cnt++);
}
ALIOS_CLI_CMD_REGISTER(ulog_encode_fs_test, uet, Console ulog encode fs test)
#endif
/* test for panic trigger in task*/
static void panic_trigger(int argc, char **argv)
{
#ifdef OS_UDF
OS_UDF();
#endif
}
ALIOS_CLI_CMD_REGISTER(panic_trigger, panic, Console trigger system panic)
/* test for fatal error trigger in task*/
static void fatal_error_trigger(int argc, char **argv)
{
assert(0);
}
ALIOS_CLI_CMD_REGISTER(fatal_error_trigger, assert, Trigger assert)
static void hung_trigger(int argc, char **argv)
{
CPSR_ALLOC();
RHINO_CPU_INTRPT_DISABLE();
(void)cpsr;
aos_msleep(1000);
}
ALIOS_CLI_CMD_REGISTER(hung_trigger, hung, Trigger system hung)
__attribute__((weak)) void alios_debug_pc_show(int argc, char **argv)
{
return;
}
ALIOS_CLI_CMD_REGISTER(alios_debug_pc_show, pcshow, Show pc addr region)
#endif /* AOS_COMP_CLI */
| YifuLiu/AliOS-Things | components/debug/src/debug_test.c | C | apache-2.0 | 2,439 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef DEBUG_TEST_H
#define DEBUG_TEST_H
#ifdef __cplusplus
extern "C" {
#endif
/* show cpu regs(armv7a)*/
void arch_regs_show(void);
#ifdef __cplusplus
}
#endif
#endif /* DEBUG_TEST_H */
| YifuLiu/AliOS-Things | components/debug/src/debug_test.h | C | apache-2.0 | 258 |
/*
* Copyright (C) 2021-2022 Alibaba Group Holding Limited
*/
#ifndef AOS_DEVFS_H
#define AOS_DEVFS_H
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <aos/kernel.h>
#include <aos/device.h>
#ifdef AOS_COMP_VFS
#include <poll.h>
#include <aos/vfs.h>
#else
#error Unsupported OS.
#endif
#define AOS_DEVFS_NODE_NAME_MAX_LEN 63
struct aos_devfs_file_ops;
typedef enum {
AOS_DEVFS_WQ_RD = 0,
AOS_DEVFS_WQ_WR,
AOS_DEVFS_WQ_MAX,
} aos_devfs_wait_queue_t;
typedef struct {
char name[AOS_DEVFS_NODE_NAME_MAX_LEN + 1];
const struct aos_devfs_file_ops *ops;
#ifdef AOS_COMP_VFS
aos_spinlock_t poll_lock;
poll_notify_t poll_notify;
struct pollfd *poll_fd;
void *poll_arg;
#else
#error Unsupported OS.
#endif
} aos_devfs_node_t;
#define AOS_DEVFS_NODE_INIT_VAL { .name = { '\0', }, .ops = NULL, }
#define aos_devfs_node_init(node) do { *(node) = (aos_devfs_node_t)AOS_DEVFS_NODE_INIT_VAL; } while (0)
#define aos_devfs_node_is_valid(node) ((node)->name[0] != '\0')
#ifdef AOS_COMP_VFS
typedef file_t aos_devfs_file_t;
typedef int aos_devfs_poll_request_t;
#else
#error Unsupported OS.
#endif
typedef struct aos_devfs_file_ops {
aos_status_t (*ioctl)(aos_devfs_file_t *file, int cmd, uintptr_t arg);
aos_status_t (*poll)(aos_devfs_file_t *file, aos_devfs_poll_request_t *req);
/* TODO: complete the argument list of mmap() */
aos_status_t (*mmap)(aos_devfs_file_t *file, ...);
ssize_t (*read)(aos_devfs_file_t *file, void *buf, size_t count);
ssize_t (*write)(aos_devfs_file_t *file, const void *buf, size_t count);
int64_t (*lseek)(aos_devfs_file_t *file, int64_t offset, int whence);
} aos_devfs_file_ops_t;
#ifdef __cplusplus
extern "C" {
#endif
aos_status_t aos_devfs_add_node(aos_devfs_node_t *node);
aos_status_t aos_devfs_remove_node(aos_devfs_node_t *node);
aos_dev_ref_t *aos_devfs_file2ref(aos_devfs_file_t *file);
mode_t aos_devfs_file_get_mode(aos_devfs_file_t *file);
uint64_t aos_devfs_file_get_position(aos_devfs_file_t *file);
void aos_devfs_file_set_position(aos_devfs_file_t *file, uint64_t pos);
void aos_devfs_poll_add(aos_devfs_node_t *node, aos_devfs_wait_queue_t wq, aos_devfs_poll_request_t *req);
void aos_devfs_poll_wakeup(aos_devfs_node_t *node, aos_devfs_wait_queue_t wq);
static inline bool aos_devfs_file_is_readable(aos_devfs_file_t *file)
{
bool ret;
switch (aos_devfs_file_get_mode(file) & O_ACCMODE) {
case O_RDONLY:
case O_RDWR:
ret = true;
break;
default:
ret = false;
break;
}
return ret;
}
static inline bool aos_devfs_file_is_writable(aos_devfs_file_t *file)
{
bool ret;
switch (aos_devfs_file_get_mode(file) & O_ACCMODE) {
case O_WRONLY:
case O_RDWR:
ret = true;
break;
default:
ret = false;
break;
}
return ret;
}
static inline int64_t aos_devfs_file_lseek_sized(aos_devfs_file_t *file, uint64_t size, int64_t offset, int whence)
{
int64_t ret;
if (size > (uint64_t)INT64_MAX)
return -EINVAL;
switch (whence) {
case SEEK_SET:
if (offset < 0 || (uint64_t)offset > size)
return -EINVAL;
ret = offset;
break;
case SEEK_CUR:
{
uint64_t cur = aos_devfs_file_get_position(file);
if ((offset > 0 && cur + (uint64_t)offset > size) || (offset < 0 && (uint64_t)(-offset) > cur))
return -EINVAL;
ret = (int64_t)cur + offset;
}
break;
case SEEK_END:
if (offset > 0 || (uint64_t)(-offset) > size)
return -EINVAL;
ret = (int64_t)size + offset;
break;
default:
return -EINVAL;
}
aos_devfs_file_set_position(file, (uint64_t)ret);
return ret;
}
#ifdef __cplusplus
}
#endif
#endif /* AOS_DEVFS_H */
| YifuLiu/AliOS-Things | components/devfs/include/aos/devfs.h | C | apache-2.0 | 3,868 |
#include <stdlib.h>
#include <stdio.h>
#include <aos/device_core.h>
#include <aos/devfs.h>
static const char path_prefix[] = "/dev/";
typedef struct {
aos_dev_ref_t ref;
} devfs_file_data_t;
static int devfs_open(inode_t *inode, file_t *file)
{
aos_devfs_node_t *node = (aos_devfs_node_t *)inode->i_arg;
aos_dev_t *dev = aos_container_of(node, aos_dev_t, devfs_node);
devfs_file_data_t *fdata;
int ret;
fdata = malloc(sizeof(*fdata));
if (!fdata)
return -ENOMEM;
ret = aos_dev_ref(&fdata->ref, dev);
if (ret) {
free(fdata);
return ret;
}
file->f_arg = fdata;
return 0;
}
static int devfs_close(file_t *file)
{
devfs_file_data_t *fdata = (devfs_file_data_t *)file->f_arg;
aos_dev_put(&fdata->ref);
free(fdata);
file->f_arg = NULL;
return 0;
}
static ssize_t devfs_read(file_t *file, void *buf, size_t count)
{
aos_devfs_node_t *node = (aos_devfs_node_t *)file->node->i_arg;
if (!node->ops->read)
return -ENOTSUP;
if (!aos_devfs_file_is_readable(file))
return -EPERM;
if (!buf || !count)
return -EINVAL;
return node->ops->read(file, buf, count);
}
static ssize_t devfs_write(file_t *file, const void *buf, size_t count)
{
aos_devfs_node_t *node = (aos_devfs_node_t *)file->node->i_arg;
if (!node->ops->write)
return -ENOTSUP;
if (!aos_devfs_file_is_writable(file))
return -EPERM;
if (!buf || !count)
return -EINVAL;
return node->ops->write(file, buf, count);
}
static int devfs_ioctl(file_t *file, int cmd, unsigned long arg)
{
aos_devfs_node_t *node = (aos_devfs_node_t *)file->node->i_arg;
if (!node->ops->ioctl)
return -ENOTSUP;
return node->ops->ioctl(file, cmd, arg);
}
static int devfs_poll(file_t *file, int flag, poll_notify_t notify, void *fd, void *arg)
{
aos_devfs_node_t *node = (aos_devfs_node_t *)file->node->i_arg;
struct pollfd *poll_fd = (struct pollfd *)fd;
aos_devfs_poll_request_t req = 0;
aos_status_t revents;
aos_irqsave_t flags;
revents = node->ops->poll ? node->ops->poll(file, &req) : -ENOTSUP;
revents = (revents < 0) ? POLLERR : revents;
if (poll_fd) {
if (poll_fd->events & revents & (POLLIN | POLLOUT | POLLERR)) {
poll_fd->revents |= revents & (POLLIN | POLLOUT | POLLERR);
notify(poll_fd, arg);
} else {
flags = aos_spin_lock_irqsave(&node->poll_lock);
node->poll_notify = notify;
node->poll_fd = poll_fd;
node->poll_arg = arg;
aos_spin_unlock_irqrestore(&node->poll_lock, flags);
}
} else {
flags = aos_spin_lock_irqsave(&node->poll_lock);
if (node->poll_fd)
node->poll_fd->revents |= revents & (POLLIN | POLLOUT | POLLERR);
node->poll_notify = NULL;
node->poll_fd = NULL;
node->poll_arg = NULL;
aos_spin_unlock_irqrestore(&node->poll_lock, flags);
}
return 0;
}
static uint32_t devfs_lseek(file_t *file, int64_t offset, int32_t whence)
{
aos_devfs_node_t *node = (aos_devfs_node_t *)file->node->i_arg;
int64_t pos;
if (!node->ops->lseek)
return (uint32_t)(-ENOTSUP);
switch (whence) {
case SEEK_SET:
case SEEK_CUR:
case SEEK_END:
break;
default:
return (uint32_t)(-EINVAL);
}
pos = node->ops->lseek(file, offset, whence);
if (pos < 0)
return (uint32_t)(int32_t)pos;
aos_devfs_file_set_position(file, pos);
return (uint32_t)aos_devfs_file_get_position(file);
}
static file_ops_t devfs_fops = {
.open = devfs_open,
.close = devfs_close,
.read = devfs_read,
.write = devfs_write,
.ioctl = devfs_ioctl,
.poll = devfs_poll,
.lseek = devfs_lseek,
.stat = NULL,
.mmap = NULL,
.access = NULL,
};
aos_status_t aos_devfs_add_node(aos_devfs_node_t *node)
{
char path[sizeof(path_prefix) - 1 + AOS_DEVFS_NODE_NAME_MAX_LEN + 1];
int path_len;
if (!node || !aos_devfs_node_is_valid(node))
return -EINVAL;
path_len = snprintf(path, sizeof(path), "%s%s", path_prefix, node->name);
if (path_len < 0 || path_len >= sizeof(path))
return -EINVAL;
aos_spin_lock_init(&node->poll_lock);
node->poll_notify = NULL;
node->poll_fd = NULL;
node->poll_arg = NULL;
return aos_register_driver(path, &devfs_fops, node);
}
aos_status_t aos_devfs_remove_node(aos_devfs_node_t *node)
{
char path[sizeof(path_prefix) - 1 + AOS_DEVFS_NODE_NAME_MAX_LEN + 1];
int path_len;
if (!node || !aos_devfs_node_is_valid(node))
return -EINVAL;
path_len = snprintf(path, sizeof(path), "%s%s", path_prefix, node->name);
if (path_len < 0 || path_len >= sizeof(path))
return -EINVAL;
(void)aos_unregister_driver(path);
return 0;
}
aos_dev_ref_t *aos_devfs_file2ref(aos_devfs_file_t *file)
{
devfs_file_data_t *fdata = (devfs_file_data_t *)file->f_arg;
return &fdata->ref;
}
mode_t aos_devfs_file_get_mode(aos_devfs_file_t *file)
{
return file->node->i_flags;
}
uint64_t aos_devfs_file_get_position(aos_devfs_file_t *file)
{
return file->offset;
}
void aos_devfs_file_set_position(aos_devfs_file_t *file, uint64_t pos)
{
file->offset = pos;
}
void aos_devfs_poll_add(aos_devfs_node_t *node, aos_devfs_wait_queue_t wq, aos_devfs_poll_request_t *req)
{
}
void aos_devfs_poll_wakeup(aos_devfs_node_t *node, aos_devfs_wait_queue_t wq)
{
aos_irqsave_t flags;
flags = aos_spin_lock_irqsave(&node->poll_lock);
if (node->poll_notify)
node->poll_notify(node->poll_fd, node->poll_arg);
node->poll_notify = NULL;
node->poll_fd = NULL;
node->poll_arg = NULL;
aos_spin_unlock_irqrestore(&node->poll_lock, flags);
}
| YifuLiu/AliOS-Things | components/devfs/src/devfs_aos.c | C | apache-2.0 | 5,880 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#if AOS_COMP_CLI
#include "aos/cli.h"
#endif
#include "aos/list.h"
#include <drivers/u_ld.h>
#include <drivers/spinlock.h>
#include <drivers/char/u_device.h>
#include <drivers/char/u_driver.h>
#include <drivers/char/u_bus.h>
static int u_bus_dump(struct u_bus *bus);
static int u_device_unbind_driver(struct u_device *dev);
static int u_bus_detach_device(struct u_device *dev);
/**
* all buses is connected via g_bus_list_head,
* used to enumerate bus/device/driver,
* either for info dump or for power management function
*
*/
static dlist_t g_bus_list_head;
static spinlock_t g_bus_list_lock;
/**
* dump all bus informations
*
* @return always returns 0
*/
int u_bus_dump_all(void) {
u_bus_t *bus = NULL;
dlist_t *next = NULL;
u_bus_private_t *p = NULL;
dlist_for_each_entry_safe(&g_bus_list_head, next, p, u_bus_private_t, bus_node) {
ddkc_info("p:%p, bus_node:%p, next:%p, prev:%p\r\n", p, &p->bus_node, p->bus_node.next, p->bus_node.prev);
bus = p->bus;
u_bus_dump(bus);
}
return 0;
}
/**
* dump single bus's information, all devices, drivers connected to this bus is included
*
* @param bus - pointer to specified bus
* @return
*/
static int u_bus_dump(struct u_bus *bus) {
u_device_t *dev = NULL;
u_driver_t *drv = NULL;
struct u_bus_private *p = NULL;
u_device_private_t *dev_p = NULL;
u_driver_private_t *drv_p = NULL;
struct dlist_s *next = NULL;
if (!bus)
return -EINVAL;
ddkc_info("bus:%p, name:%s, p:%p\r\n", bus, bus->name, bus->p);
p = bus->p;
/* dump information of all devices, who is connected into current bus */
if (dlist_empty(&p->dev_list)) {
ddkc_warn("bus[%s]'s device list is empty\r\n", bus->name);
} else {
dlist_for_each_entry_safe(&p->dev_list, next, dev_p, u_device_private_t, bus_node) {
dev = dev_p->dev;
u_device_dump(dev);
}
}
/* dump information of all drivers, who is connected into current bus */
if (dlist_empty(&p->drv_list)) {
ddkc_warn("bus[%s]'s driver list is empty\r\n", bus->name);
} else {
dlist_for_each_entry_safe(&p->drv_list, next, drv_p, u_driver_private_t, bus_node) {
drv = drv_p->drv;
u_driver_dump(drv);
}
}
return 0;
}
/**
* connect dev into target bus(dev->bus)
* low level operations, driver is not aware of this operation
*
* @param dev - pointer to target device
* @return always returns 0
*/
int u_bus_add_device(struct u_device *dev) {
unsigned long flags;
u_bus_t *bus = dev->bus;
/* add dev->p->bus_node into dev->bus's p->dev_list */
spin_lock_irqsave(&bus->p->lock, flags);
dlist_add_tail(&dev->p->bus_node, &bus->p->dev_list);
spin_unlock_irqrestore(&bus->p->lock, flags);
return 0;
}
/**
* disconnect device with its driver and delete it from target bus(dev->bus)
*
* @param dev - pointer to target device
* @return always return 0
*/
int u_bus_del_device(struct u_device *dev) {
u_bus_t *bus = NULL;
if (!dev) {
ddkc_err("invalid dev:%p to delete\r\n", dev);
return -EINVAL;
}
bus = dev->bus;
/* if device is already attached with specified driver, detach it */
if (dev && dev->drv) {
u_bus_detach_device(dev);
u_device_unbind_driver(dev);
}
/* delete dev from it's bus */
if (dev && dev->bus && !dlist_empty(&dev->bus->p->dev_list)) {
//TODO: should notify driver about this device is to be deleted?
unsigned long flags;
spin_lock_irqsave(&bus->p->lock, flags);
dlist_del(&dev->p->bus_node);
dlist_init(&dev->p->bus_node);
spin_unlock_irqrestore(&bus->p->lock, flags);
}
return 0;
}
/**
* bind device with target driver
*
* @param drv - pointer to the driver to be binded
* @param dev - pointer to the device to be binded
* @return always return 0
*/
static int u_driver_bind_device(struct u_driver *drv, struct u_device *dev) {
unsigned long flags;
u_driver_private_t *drv_p = drv->p;
u_device_private_t *dev_p = dev->p;
spin_lock_irqsave(&drv_p->lock, flags);
dlist_add_tail(&dev_p->drv_node, &drv_p->dev_list);
spin_unlock_irqrestore(&drv_p->lock, flags);
return 0;
}
/**
* unbind device with the binded driver
*
* @param dev - pointer to target device
* @return always returns 0
*/
static int u_device_unbind_driver(struct u_device *dev) {
unsigned long flags;
u_device_private_t *dev_p = dev->p;
spin_lock_irqsave(&dev_p->lock, flags);
dlist_del(&dev_p->drv_node);
spin_unlock_irqrestore(&dev_p->lock, flags);
return 0;
}
/**
* Try to init dev with drv's ops
*
* @param drv - target driver to be used for device initialization
* @param dev - target device to be initialized
* @return return 1 if init success; otherwise return 0
*/
static int u_driver_init_device(struct u_driver *drv, struct u_device *dev)
{
int r = -1;
/* attach to drv for the moment, will detach if init/probe fails */
dev->drv = drv;
ddkc_dbg("bus[%s] try to init dev[%s] with drv[%s]\r\n", dev->bus->name, dev->name, drv->name);
ddkc_dbg("dev->bus->init:%p, drv->init:%p\r\n", dev->bus->init, drv->init);
ddkc_dbg("dev->bus->probe:%p, drv->probe:%p\r\n", dev->bus->probe, drv->probe);
do {
/* try legacy ops, bus init cb is prioritized */
if (dev->bus->init) {
r = dev->bus->init(dev);
break;
} else if (drv->init) {
r = drv->init(dev);
break;
}
/* try probe ops - for linux-like drivers, bus probe cb is prioritized */
if (dev->bus->probe) {
r = dev->bus->probe(dev);
break;
} else if (drv->probe) {
r = drv->probe(dev);
break;
}
} while(0);
if (!r) {
ddkc_dbg("bus[%s] drv[%s] init dev[%s] success\r\n", dev->bus->name, drv->name, dev->p->name);
u_driver_bind_device(drv, dev);
} else {
ddkc_warn("bus[%s] drv[%s] init dev[%s] fails\r\n", dev->bus->name, drv->name, dev->name);
dev->drv = NULL;
}
return r;
}
/**
* Try whether drv matches dev with bus match function
*
* @param drv - target driver to be matched with dev
* @param dev - target device to be matched with drv
* @return return 1 if match success; otherwise return 0
*/
static int u_driver_match_device(struct u_driver *drv, struct u_device *dev)
{
if (!drv || !dev) {
ddkc_err("invalid drv:%p or dev:%p\r\n", drv, dev);
return 0;
}
ddkc_dbg("driver match device, drv:%p, drv->bus:%p, dev:%p\r\n", drv, drv->bus, dev);
if (drv->bus) {
ddkc_dbg("driver match device, drv->bus->match:%p\r\n", drv->bus->match);
return drv->bus->match ? drv->bus->match(dev, drv) : 1;
} else {
ddkc_err("invalid drv->bus:%p\r\n", drv->bus);
return 0;
}
}
/**
* enumerate driver list and try to init the device with the drivers
*
* @param dev - pointer to the deviice to be initialized
*
* @return 0 if device initialization success; negative if device initialization fails
*/
int u_bus_try_init_device(struct u_device *dev) {
int r = 0;
u_bus_t *bus = dev->bus;
u_driver_t *drv = NULL;
u_driver_private_t *drv_p = NULL;
struct dlist_s *next = NULL;
if (dev->drv) {
ddkc_warn("dev[%s]'s is busy, is now driven by drv[%s]\r\n", dev->name, dev->drv->name);
return 0;
}
// whenever device is created, try match and init it if match returns true
if (dlist_empty(&bus->p->drv_list)) {
ddkc_dbg("bus[%s]'s drv_list is empty\r\n", bus->name);
return 0;
}
dlist_for_each_entry_safe(&bus->p->drv_list, next, drv_p, u_driver_private_t, bus_node) {
drv = drv_p->drv;
r = u_driver_match_device(drv, dev);
if (!r) {
ddkc_dbg("drv[%s] does not match dev[%s]\r\n", drv->name, dev->name);
continue;
}
r = u_driver_init_device(drv, dev);
if (r) {
ddkc_err("drv[%s] init dev[%s] fails\r\n", drv->name, dev->name);
} else {
ddkc_info("drv[%s] init dev[%s] success\r\n", drv->name, dev->name);
}
}
return 0;
}
/**
* add a driver into bus's driver list
*
* @param drv - the driver to be added
* @return always return 0
*/
int u_bus_add_driver(struct u_driver *drv) {
u_bus_t *bus = drv->bus;
unsigned long flags;
spin_lock_irqsave(&bus->p->lock, flags);
dlist_add_tail(&drv->p->bus_node, &bus->p->drv_list);
spin_unlock_irqrestore(&bus->p->lock, flags);
return 0;
}
/**
* attach a driver into bus's driver list,
* try to init free devices(not drived by any driver) if device is matchd
*
* @drv: the driver to be added
* @return always return 0
*/
int u_bus_attach_driver(struct u_driver *drv) {
int r = 0;
u_bus_t *bus = drv->bus;
u_device_t *dev = NULL;
u_device_private_t *dev_p = NULL;
dlist_t *next = NULL;
// whenever device is created, try init it if match returns success
if (dlist_empty(&bus->p->dev_list)) {
ddkc_dbg("bus[%s]'s dev_list is empty\r\n", bus->name);
return 0;
}
/* try to match the device in bus device list with driver */
dlist_for_each_entry_safe(&bus->p->dev_list, next, dev_p, u_device_private_t, bus_node) {
dev = dev_p->dev;
/* exclude the devices who is already attached by driver */
if (dev->drv) {
ddkc_dbg("bus[%s] dev[%s] is already probed by drv[%s]\r\n",
bus->name, dev->p->name, dev->drv->name);
continue;
}
r = u_driver_match_device(drv, dev);
if (!r) {
ddkc_dbg("drv[%s] does not match dev[%s]\r\n", drv->name, dev->name);
continue;
}
r = u_driver_init_device(drv, dev);
ddkc_dbg("drv[%s] init dev[%s] %s, r:%d\r\n", drv->name, dev->name, r ? "fail" : "success", r);
}
return 0;
}
u_bus_t * u_bus_get_by_name(char *name) {
dlist_t *next = NULL;
u_bus_private_t *p = NULL;
u_bus_t *bus = NULL;
if (!name)
return NULL;
dlist_for_each_entry_safe(&g_bus_list_head, next, p, u_bus_private_t, bus_node) {
u_bus_dump(p->bus);
bus = p->bus;
ddkc_dbg("bus->name:%s, name_len:%d\r\n", bus->name, strlen(bus->name));
if (!strcmp(bus->name, name)) {
ddkc_dbg("name:%s, bus:%p\r\n", name, bus);
break;
}
bus = NULL;
}
return bus;
}
/**
* init global bus list, this is module entry API of u_bus
* @return always return 0
*/
int u_bus_list_init(void) {
ddkc_dbg("bus list init\r\n");
dlist_init(&g_bus_list_head);
spin_lock_init(&g_bus_list_lock);
return 0;
}
/**
* add new bus into global bus list
*
* @param bus - pointer to target bus to be added
* @return always return 0
*/
int u_bus_add(struct u_bus *bus) {
unsigned long flags;
ddkc_dbg("add bus[%s] into global bus list\r\n", bus->name);
spin_lock_irqsave(&g_bus_list_lock, flags);
dlist_add_tail(&bus->p->bus_node, &g_bus_list_head);
spin_unlock_irqrestore(&g_bus_list_lock, flags);
return 0;
}
/**
* init bus node struct
*
* @param bus - target bus to be initialized
* @return 0 for success; negative for failure
*/
int u_bus_node_initialize(struct u_bus *bus) {
u_bus_private_t *p = NULL;
p = (u_bus_private_t *)malloc(sizeof(u_bus_private_t));
if (!p) {
ddkc_err("malloc for u_bus_private_t fails\r\n");
return -ENOMEM;
}
spin_lock_init(&p->lock);
dlist_init(&p->dev_list);
dlist_init(&p->drv_list);
dlist_init(&p->bus_node);
p->bus = bus;
bus->p = p;
return 0;
}
/**
* register bus to system
*
* @param bus - pointer to the target bus to be registered
* @return 0 for success; negative for failure
*/
int u_bus_register(struct u_bus *bus) {
int r = 0;
if(!bus) {
ddkc_err("invalid bus:%p\r\n", bus);
return -EINVAL;
}
if (bus->p || !bus->name) {
ddkc_err("invalid bus priv data:%p or bus name:%p, ignore\r\n", bus->p, bus->name);
return -EINVAL;
}
r = u_bus_node_initialize(bus);
if (r) {
ddkc_err("bus node init fails, error:%d\r\n", r);
return -1;
}
return u_bus_add(bus);
}
/**
* unregister bus from system
*
* @param bus - pointer to the target bus to be unregistered
* @return
*/
int u_bus_unregister(struct u_bus *bus) {
unsigned long flags;
// TODO: all bus related driver/device list should be clean up before calling u_bus_unregister
ddkc_info("add bus[%s] into global bus list\r\n", bus->name);
spin_lock_irqsave(&g_bus_list_lock, flags);
dlist_del(&bus->p->bus_node);
spin_unlock_irqrestore(&g_bus_list_lock, flags);
return 0;
}
#if 0
struct u_device *u_bus_find_dev_by_id(struct u_bus *bus, dev_t devid) {
u_device_t *dev = NULL;
struct u_driver_t *drv = NULL;
struct u_bus_private *p = NULL;
u_device_private_t *dev_p = NULL;
struct dlist_s *next = NULL;
if (!bus)
return -EINVAL;
ddkc_info("bus:%p, name:%s, p:%p, devid:0x%x\r\n", bus, bus->name, bus->p, devid);
p = bus->p;
if (dlist_empty(&p->dev_list)) {
ddkc_dbg("bus[%s]'s device list is empty\r\n", bus->name);
}
dlist_for_each_entry_safe(&p->dev_list, next, dev_p, u_device_private_t, bus_node) {
dev = dev_p->dev;
if (dev->dev_id == devid) {
ddkc_loud("dev:%p found with devid:0x%x\r\n", dev, devid);
break;
}
ddkc_loud("dev->dev_id:%d\r\n", dev->dev_id);
dev = NULL;
}
return dev;
}
struct u_device *u_device_find_by_devid(dev_t devid) {
u_bus_t *bus = NULL;
dlist_t *pos = NULL;
dlist_t *next = NULL;
u_bus_private_t *p = NULL;
struct u_device *dev = NULL;
ddkc_dbg ("%s\r\n", __func__);
dlist_for_each_entry_safe(&g_bus_list_head, next, p, u_bus_private_t, bus_node) {
bus = p->bus;
dev = u_bus_find_dev_by_id(bus, devid);
if (dev)
break;
}
ddkc_err("u_device[%p] found by devid[0x%x]\r\n", dev, devid);
return dev;
}
#endif
/**
* delete a driver from bus's driver list
*
* @param drv - pointer to the driver to be deleted
* @return always return 0
*/
int u_bus_del_driver(struct u_driver *drv) {
u_bus_t *bus = NULL;
unsigned long flags;
if (!drv) {
ddkc_err("invalid drv:%p to delete\r\n", drv);
return -EINVAL;
}
bus = drv->bus;
spin_lock_irqsave(&bus->p->lock, flags);
dlist_del(&drv->p->bus_node);
spin_unlock_irqrestore(&bus->p->lock, flags);
return 0;
}
/**
* Try to deinit a device
*
* @param drv - pointer to target device's driver
* @param dev - pointer to target device
* @return 0 if deinit success; otherwise return negative
*/
static int u_driver_deinit_device(struct u_driver *drv, struct u_device *dev)
{
int r = -1;
/* attach to drv for the moment, will detach if init fails */
ddkc_dbg("bus[%s] drv[%s] removing dev[%s]\r\n", dev->bus->name, drv->name, dev->name);
ddkc_dbg("dev->bus->deinit:%p, drv->deinit:%p\r\n", dev->bus->deinit, drv->deinit);
ddkc_dbg("dev->bus->remove:%p, drv->remove:%p\r\n", dev->bus->remove, drv->remove);
/* try legacy ops */
if (dev->bus->deinit) {
r = dev->bus->deinit(dev);
if (r)
goto remove_fail;
} else if (drv->deinit) {
r = drv->deinit(dev);
if (r)
goto remove_fail;
}
if (dev->bus->remove) {
r = dev->bus->remove(dev);
if (r)
goto remove_fail;
} else if (drv->remove) {
r = drv->remove(dev);
if (r)
goto remove_fail;
}
dev->drv = NULL;
ddkc_dbg("bus[%s] drv[%s] remove dev[%s] success\r\n", dev->bus->name, drv->name, dev->p->name);
return 0;
remove_fail:
dev->drv = NULL;
ddkc_dbg("bus[%s] drv[%s] remove dev[%s] fails\r\n", dev->bus->name, drv->name, dev->name);
return -1;
}
/**
* deattch a driver into bus's driver list
*
* @param drv - pointer to target driver to be deatched
* @return always return 0
*/
int u_bus_detach_driver(struct u_driver *drv) {
int r = 0;
u_device_t *dev = NULL;
u_device_private_t *dev_p = NULL;
dlist_t *next = NULL;
if (dlist_empty(&drv->p->dev_list)) {
ddkc_dbg("drv[%s]'s dev_list is empty\r\n", drv->name);
return 0;
}
ddkc_dbg("drv:%p, drv->p:%p, &drv->p->dev_list:%p\r\n", drv, drv->p, &drv->p->dev_list);
/* try to remove the devices which is already attached with the driver */
dlist_for_each_entry_safe(&drv->p->dev_list, next, dev_p, u_device_private_t, drv_node) {
ddkc_dbg("dev:%p, dev_p:%p\r\n", dev, dev_p);
dev = dev_p->dev;
ddkc_dbg("dev:%p, dev_p:%p\r\n", dev, dev_p);
r = u_driver_deinit_device(drv, dev);
ddkc_dbg("drv[%s] remove dev[%s] %s, r:%d\r\n", drv->name, dev->name, r ? "fail" : "success", r);
}
return 0;
}
/**
* detach a device into bus's driver list
*
* @param dev - target device to be detached
* @return always return 0
*/
int u_bus_detach_device(struct u_device *dev) {
int r = 0;
u_driver_t *drv = dev->drv;
if (!drv) {
ddkc_dbg("dev[%s] is not attached to driver\r\n", dev->name);
return 0;
}
r = u_driver_deinit_device(drv, dev);
if (r) {
ddkc_err("dev[%s] deatch with driver[%s] failed\r\n", dev->name, drv->name);
return 0;
}
ddkc_dbg("dev[%s] deatch with driver[%s] succeed\r\n", dev->name, drv->name);
return 0;
}
#if AOS_COMP_CLI
/**
* command service handler - dump information of all bus/device/driver
*
*/
static void u_bus_dump_cmd(char *wbuf, int len, int argc, char **argv) {
ddkc_info("dumping bus/device/driver information\r\n");
u_bus_dump_all();
ddkc_info("dump bus/device/driver information done\r\n");
return;
}
struct cli_command u_bus_test_cmds[] = {
{"ubusdump", "dump system's bus/device/driver information", u_bus_dump_cmd},
};
static int u_bus_test_cmd_init(void) {
ddkc_dbg("registering udevice commands\r\n");
return aos_cli_register_commands(&u_bus_test_cmds[0],
sizeof(u_bus_test_cmds)/sizeof(u_bus_test_cmds[0]));
}
#endif /* AOS_COMP_CLI */
/**
* u_bus module init entry
* declared with CORE_DRIVER_ENTRY, which is 1st level driver init entry
* @return 0
*/
int u_bus_init(void) {
#if AOS_COMP_CLI
u_bus_test_cmd_init();
#endif
return u_bus_list_init();
}
CORE_DRIVER_ENTRY(u_bus_init)
| YifuLiu/AliOS-Things | components/drivers/core/base/core/u_bus.c | C | apache-2.0 | 17,544 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <errno.h>
#include "aos/list.h"
#include <drivers/char/u_cdev.h>
#include <drivers/char/u_device.>
int g_cdev_log_level = CDEV_LOG_DEBUG;
//TODO: need to add lock to protect operations on g_cdev_list_head
dlist_t g_cdev_list_head;
#ifdef ENABLE_U_CHAR_DEV_DUMP
static int u_cdev_dump(u_cdev_t *dev);
static int u_cdev_dump_all(void);
/**
* 1. 怎样生成path name , 像ttyS0这种index怎样带进去? device_add -> kobject_event(&dev->kobj, KOBJ_ADD)
* 2. 当open操作到来的时候,回传一个handle object来记录thread, cdev, major no./minor no.等信息
* 3. 后续read/write, 用handle找到对应的device
* */
int u_cdev_dump(u_cdev_t *dev) {
cdev_info("dev[%p] dev_id[%x] count[%d], ops[%p]\r\n", dev, dev->dev_id, dev->count, dev->ops);
return 0;
}
int u_cdev_dump_all(void) {
u_cdev_t *dev_p = NULL;
/* add to global cdev list */
dlist_for_each_entry(&g_cdev_list_head, dev_p, u_cdev_t, node) {
u_cdev_dump(dev_p);
}
return 0;
}
#else
#define u_cdev_dump(x)
#define u_cdev_dump_all()
#endif
/**
* u_cdev_init - u_cdev_t struct init and add file operation hook
*
* @dev: pointer to target char dev to be initialized
* @fops: file operation struct hook to this char device
* */
int u_cdev_init(u_cdev_t *dev, /*struct u_file_operations*/void *fops) {
if (!dev || !fops) {
cdev_err("invalid dev:%p or fops:%p\r\n", dev, fops);
return -EINVAL;
}
/** check whether dev->ops is already assigned,
* if yes, it must be same with fops; return -EINVAL otherwise
* */
if (dev->ops) {
if (dev->ops != fops) {
cdev_err("dev->ops:%p != fops:%p, ignore\r\n", dev->ops, fops);
return -EINVAL;
} else {
cdev_warn("dev->ops is already assigned, ignore\r\n", dev->ops);
return 0;
}
}
dev->ops = fops;
dev->thread_ctx = NULL;
dlist_init(&dev->node);
cdev_dbg("dev:%p init done, id:%d, fops:%p\r\n", dev, dev->dev_id, fops);
return 0;
}
/**
* u_cdev_add - add a new char dev into a global char device list
* @dev: pointer to target char dev to be added
* @devid: target char char device's device id
* @count: minor device number
* */
int u_cdev_add(u_cdev_t *dev, unsigned int devid, unsigned int count) {
u_cdev_t *dev_p = NULL;
if (!dev || !MAJOR(devid)) {
cdev_err("invalid dev:%p, or devid:%x\r\n", dev, devid);
return -EINVAL;
}
dev->dev_id = devid;
dev->count = count;
u_cdev_dump(dev);
/* add to global cdev list with sorted sequence */
dlist_for_each_entry(&g_cdev_list_head, dev_p, u_cdev_t, node) {
if (devid > dev_p->dev_id)
continue;
if (devid == dev_p->dev_id) {
if (dev_p->ops) {
cdev_err("same devid[%x], different ops[%p, %p], fail to add cdev\r\n",
devid, dev_p->ops, dev->ops);
return -EBUSY;
} else {
dev->thread_ctx = pthread_self();
dlist_add(&dev->node, &dev_p->node); // add the new one
dlist_del(&dev_p->node); // delete the old one
free(dev_p);
cdev_dbg("same devid:%x found, replace it, thread_ctx:%p\r\n", devid, dev->thread_ctx);
u_cdev_dump_all();
return 0;
}
}
dev->thread_ctx = pthread_self();
dlist_add_tail(&dev->node, &dev_p->node);
cdev_dbg("devid:%x added, thread_ctx:%p\r\n", devid, dev->thread_ctx);
u_cdev_dump_all();
return 0;
}
dev->thread_ctx = pthread_self();
dlist_add_tail(&dev->node, &g_cdev_list_head);
cdev_dbg("devid:%x added, thread_ctx:%p\r\n", devid, dev->thread_ctx);
u_cdev_dump_all();
return 0;
}
u_cdev_t * u_cdev_find_node_by_name(char *pathname) {
u_cdev_t *dev_p = NULL;
u_dev_node_t *dev_node = NULL;
unsigned int dev_id = 0;
if (!strncmp(pathname, "/dev/", sizeof("/dev/")))
dev_node = u_device_node_find_by_pathname(pathname);
else
dev_node = u_device_node_find_by_nodename(pathname);
if (!dev_node) {
cdev_err("device node with name[%s] not found\r\n", pathname);
return NULL;
}
dev_id = dev_node->dev_id;
dlist_for_each_entry(&g_cdev_list_head, dev_p, u_cdev_t, node) {
if (dev_id == dev_p->dev_id) {
cdev_dbg("cdev found for %s, devid:%d\r\n", pathname, dev_id);
return dev_p;
}
}
cdev_dbg("cdev not found for %s\r\n", pathname);
return NULL;
}
u_cdev_t * u_cdev_find_node_by_devid(unsigned int devid) {
u_cdev_t *dev_p = NULL;
dlist_for_each_entry(&g_cdev_list_head, dev_p, u_cdev_t, node) {
if (devid == dev_p->dev_id) {
cdev_dbg("cdev found for devid:%d\r\n", devid);
return dev_p;
}
cdev_loud("u_cdev:%p, dev_id:0x%x\r\n", dev_p, devid);
}
cdev_warn("cdev not found for %d\r\n", devid);
return NULL;
}
int u_cdev_del(u_cdev_t *dev) {
int r = -EBUSY;
u_cdev_t *dev_p = NULL;
if (!dev) {
cdev_err("invalid dev:%p\r\n", dev);
return -EINVAL;
}
/* remove cdev from global cdev list */
dlist_for_each_entry(&g_cdev_list_head, dev_p, u_cdev_t, node) {
// TODO: check whether device is in use or not
if (dev_p == dev) {
dlist_del(&dev->node);
r = 0;
break;
}
}
cdev_dbg("dev[%p] with dev_id[%d] is %s\r\n", dev, dev->dev_id, !r ? "removed" : "not found");
return r;
}
/**
*
* @param major: major number of the device to be allocated
* @param minor: start minor number of the device to bea located
* @param count: subdevice number
* @return major number of the device if success; negative number if fails
*/
int __register_u_cdev_region(unsigned int major,
unsigned int minor,
int count)
{
// TODO: should check return value of u_cdev_add
int last_maj = 0;
int last_min = 0;
int last_count = 0;
u_cdev_t *dev_p = NULL;
u_cdev_t *new = NULL;
new = malloc(sizeof(*new));
if (!new) {
cdev_err("malloc for u_cdev_t failed\r\n");
return -ENOMEM;
}
memset(new, 0, sizeof(*new));
dlist_init(&new->node);
/* dev_id in g_cdev_list_head is ordered */
if(dlist_empty(&g_cdev_list_head)) {
/* major starts from 1 */
// TODO: define DYN_MAJOR_NO_START 256 ?
major = major ? major : 1;
u_cdev_add(new, MKDEV(major, minor), count);
cdev_dbg("empty, add 1st dev, dev:%p, devid:0x%x, count:%d, ops:%p\r\n",
new, new->dev_id, count, new->ops);
return major;
}
dlist_for_each_entry_reverse(dev_p, &g_cdev_list_head, node, u_cdev_t) {
last_maj = MAJOR(dev_p->dev_id);
last_min = MINOR(dev_p->dev_id);
last_count = dev_p->count;
cdev_dbg("last_maj:%d, last_min:%d, last_count:%d\r\n", last_maj, last_min, last_count);
if (!major) {
major = last_maj + 1;
u_cdev_add(new, MKDEV(major, minor), count);
cdev_dbg("add dev, dev:%p, devid:0x%x, count:%d, ops:%p\r\n",
new, new->dev_id, count, new->ops);
return major;
}
if (major > last_maj) {
u_cdev_add(new, MKDEV(major, minor), count);
cdev_dbg("add dev:%p, devid:0x%x, count:%d, ops:%p\r\n",
new, new->dev_id, count, new->ops);
return major;
}
if (major == last_maj) {
#if 1
if (MKDEV(major, minor) >= dev_p->dev_id + last_count)
continue; // check whether there's multiple cdev with the same major number
else if (MKDEV(major, minor) + count <= dev_p->dev_id)
continue; // check whether there's multiple cdev with the same major number
else
return -EINVAL;
#else
cdev_err("major id:%d equls with already existed device, not allowed\r\n", major);
free(new);
new = NULL;
return -EINVAL; // not allowed
#endif
}
}
u_cdev_add(new, MKDEV(major, minor), count);
cdev_dbg("empty, add 1st dev, dev:%p, devid:0x%x, count:%d, ops:%p\r\n",
new, new->dev_id, count, new->ops);
return major;
}
/**
*
* @param dev_id: device id of the device if the region is allocated successfully
* @param minor: start minor number
* @param count: subdevice number
* @return major number if success, otherwise return negative number
*/
int alloc_u_cdev_region(unsigned int *dev_id, unsigned int minor, unsigned int count)
{
int major = -1;
if (!count || !dev_id) {
cdev_err("invalid count[%d]\r\n", count);
return -EINVAL;
}
major = __register_u_cdev_region(0, minor, count);
if (major <= 0) {
cdev_err("fail to alloc major number, major:%d\r\n", major);
return -1;
}
*dev_id = MKDEV(major, minor);
cdev_loud("major:%d, minor:%d, dev_id:%d, sizeof(*dev_id):%d\r\n", major, minor, *dev_id, sizeof(*dev_id));
return major;
}
int register_u_cdev_region(unsigned dev_id, unsigned count) {
int r = __register_u_cdev_region(MAJOR(dev_id), MINOR(dev_id), count);
if (r == MAJOR(dev_id))
return 0;
else {
cdev_err("register cdev region fails, r:%d\r\n", r);
return -1;
}
}
int unregister_u_cdev_region(unsigned dev_id, unsigned count) {
u_cdev_t *dev_p = NULL;
dlist_for_each_entry(&g_cdev_list_head, dev_p, u_cdev_t, node) {
/* only check major number, ignore minor number */
if (/* MAJOR(dev_id) == MAJOR(dev_p->dev_id)*/dev_id == dev_p->dev_id) {
cdev_dbg("%p with devid:0x%x is removed from global char dev list\r\n",
dev_p, dev_p->dev_id);
dlist_del(&dev_p->node); // remove it from the list
free(dev_p);
break;
}
}
dev_p = NULL;
u_cdev_dump_all();
return 0;
}
int u_cdev_module_init(void) {
dlist_init(&g_cdev_list_head);
return 0;
}
#include "drivers/u_ld.h"
CORE_DRIVER_ENTRY(u_cdev_module_init)
| YifuLiu/AliOS-Things | components/drivers/core/base/core/u_cdev.c | C | apache-2.0 | 9,229 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <stddef.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#if AOS_COMP_CLI
#include "aos/cli.h"
#endif
#include "aos/list.h"
#include <drivers/char/u_device.h>
#include <drivers/char/u_driver.h>
#include <drivers/char/u_bus.h>
#include <drivers/spinlock.h>
#define G_ROOT_PATH "/dev"
int g_ddkc_log_level = DDKC_LOG_WARN;
static dlist_t g_dev_node_list;
static u_dev_node_t *g_root_dev_node = NULL;
char ddkc_level_tag[] = {
'L',
'D',
'I',
'W',
'E'
};
/**
* dump device's information, name, id, parent, bus, driver, drv_data included
* @param dev - pointer to target device
* @return 0 for success; netative for failure
*/
int u_device_dump(struct u_device *dev) {
if (!dev) {
ddkc_err("dev is NULL\r\n");
return -1;
}
ddkc_info("dev:%p, dev->name:%s, id:%d, dev_id:%d, parent:%p, bus:%p, drv:%p, drv_data:%p\r\n",
dev, dev->name,
dev->id, dev->dev_id,
dev->parent, dev->bus, dev->drv, dev->driver_data);
return 0;
}
/**
* initialize u_device's private info
*
* @param dev - pointer to target device
* @return 0 for success; netative for failure
*/
int u_device_initialize(struct u_device *dev) {
u_device_private_t *p = NULL;
/* dev is not NULL, guaranteed by caller */
dev->drv = NULL;
/* device's parent and bus should be setup before call u_device_initialize */
//dev->parent = NULL;
//dev->bus = NULL;
p = (u_device_private_t *)malloc(sizeof(u_device_private_t));
if (!p) {
ddkc_err("malloc for u_device_private_t failed\r\n");
return -ENOMEM;
}
p->name = NULL;
spin_lock_init(&p->lock);
dlist_init(&p->bus_node);
dlist_init(&p->drv_node);
dlist_init(&p->child_head);
dlist_init(&p->parent_node);
p->dev = dev;
dev->p = p;
return 0;
}
/**
* add device into bus device list
* conditions to check in u_device_add:
* 1. dev is not NULL
* 2. dev->bus is assigned correctly
* 3. dev->p is allocated and initialized
*
* @param dev - pointer to target device
* @return 0 for success; netative for failure
*/
int u_device_add(struct u_device *dev) {
u_device_private_t *p = NULL;
int r = 0;
int len = 0;
/* dev is not NULL, guaranteed by caller */
if (!dev || !dev->p || !dev->bus) {
ddkc_err("invalid dev:%p or dev->p:%p or dev->bus:%p\r\n", dev, dev ? dev->p : NULL, dev ? dev->bus : NULL);
return -EINVAL;
}
if (!dev->bus->name || (dev->id >= MAX_DEV_ID_NUM)){
ddkc_err("invalid bus name:%p or dev->id:%d\r\n", dev->bus->name, dev->id);
return -EINVAL;
}
p = dev->p;
len = strlen(dev->bus->name) + MAX_DEV_ID_DIGS + 1; // 1 is for '\0'
p->name = (char *)malloc(len);
if (!p->name) {
ddkc_err("malloc for dev->p->name failed, len:%d\r\n", len);
return -ENOMEM;
}
/* name dev's name with <bus_name><dev_id> */
memset(p->name, 0, len);
snprintf(p->name, len, "%s%d", dev->bus->name, dev->id);
/* add device into its parent's child_head */
if (dev->parent) {
unsigned long flags;
spin_lock_irqsave(&dev->parent->p->lock, flags);
dlist_add_tail(&p->parent_node, &dev->parent->p->child_head);
spin_unlock_irqrestore(&dev->parent->p->lock, flags);
}
/* add this device into target bus */
r = u_bus_add_device(dev);
if (r)
goto dev_add_error;
/* it is not necessary to check u_bus_try_init_device's return value */
u_bus_try_init_device(dev);
return 0;
dev_add_error:
if (p->name) {
free(p->name);
p->name = NULL;
}
return r;
}
/**
* register a device into system
*
* @param dev - pointer to target device
* @return 0 for success; netative for failure
*/
int u_device_register(struct u_device *dev) {
if (!dev) {
ddkc_err("invalid dev:%p\r\n", dev);
return -EINVAL;
}
u_device_initialize(dev);
return u_device_add(dev);
}
/**
* check whether a device is registered or not
* @param dev - pointer to the device to be checked
*
* @return 0 for success; netative for failure
*/
int u_device_is_registered(struct u_device *dev) {
u_device_private_t *devp = dev->p;
if (!devp || dlist_empty(&devp->bus_node))
return 0;
return 1;
}
unsigned int u_dev_node_get_pathname_length(u_dev_node_t *dev_node) {
unsigned int length = 0;
#if 0
u_dev_node_t *parent = dev_node;
do {
if(!strlen(parent->name))
break;
length += strlen(parent->name) + 1;
parent = dev_node->parent;
} while (parent);
#else
/* 2 is for '/' and '\0' */
length = strlen(dev_node->name) + strlen(dev_node->parent->path_name) + 2;
#endif
return length;
}
char *u_dev_node_get_pathname(u_dev_node_t *dev_node) {
char *pathname = NULL;
unsigned int len = 0;
unsigned int length = u_dev_node_get_pathname_length(dev_node);
pathname = malloc(length);
if (!pathname) {
ddkc_err("malloc for pathname failed, len[%d]\r\n", length);
return NULL;
}
memset(pathname, 0, length);
#if 0
u_dev_node_t *parent = dev_node;
length -= 2;
do {
len = strlen(parent->name);
if(!len)
break;
strncpy(pathname[length - len], parent->name, len);
length -= len;
pathname[length--] = '/';
parent = dev_node->parent;
} while (parent);
#else
ddkc_dbg("pathname length:%d\r\n", length);
ddkc_dbg("parent pathname:%s\r\n", dev_node->parent->path_name);
ddkc_dbg("node pathname:%p - %s\r\n", dev_node->name, dev_node->name);
len = strlen(dev_node->parent->path_name);
if (len) {
strncpy(pathname, dev_node->parent->path_name, len);
pathname[len++] = '/';
}
strncpy(pathname + len, dev_node->name, strlen(dev_node->name));
#endif
ddkc_info("pathname:%s\r\n", pathname);
return pathname;
}
struct u_dev_node * u_device_node_create(struct u_dev_node *parent, unsigned int dev_id, void *drv_data, char *name) {
u_dev_node_t *dev_node = NULL;
if (!name) {
ddkc_err("name should not be NULL\r\n");
return NULL;
}
/**
* //TODO: need to do sanity check
* 1. whether dev_id is already binded with exist device node?
* 2. whether name is already binded to parent?
*/
// manage all device, registered with u_device_node_create, into one list,
// <pathname, dev_id> is in this list
dev_node = malloc(sizeof(u_dev_node_t) + strlen(name) + 1);
memset(dev_node, 0, sizeof(u_dev_node_t) + strlen(name) + 1);
dlist_init(&dev_node->node);
dev_node->dev_id = dev_id;
if (parent)
dev_node->parent = parent;
else
dev_node->parent = g_root_dev_node;
if (drv_data)
dev_node->drv_data = drv_data;
strncpy(dev_node->name, name, strlen(name));
dev_node->name[strlen(name)] = '\0';
// compose device pathname
dev_node->path_name = u_dev_node_get_pathname(dev_node);
ddkc_info("path_name:%s added\r\n", dev_node->path_name);
// enqueue to global device node
dlist_add(&dev_node->node, &g_dev_node_list);
/* TODO: send IPC message to notify VFS new device node is created */
return dev_node;
}
int u_device_node_delete(unsigned int dev_id) {
u_dev_node_t *dev_node = NULL;
struct dlist_s *node = NULL;
dlist_for_each_entry_safe(&g_dev_node_list, node, dev_node, u_dev_node_t, node) {
if (dev_node->dev_id == dev_id) {
dlist_del(&dev_node->node);
// free full path name memory
if (dev_node->path_name)
free(dev_node->path_name);
// free device node struct
free(dev_node);
}
}
return 0;
}
#if 0
struct u_dev_node * u_device_node_find_by_devid(dev_t dev_id) {
struct u_dev_node *parent;
u_dev_node_t *dev_node = NULL;
struct dlist_s *node = NULL;
dlist_for_each_entry_safe(&g_dev_node_list, node, dev_node, u_dev_node_t, node) {
if (dev_node->dev_id == dev_id) {
return dev_node;
}
}
return NULL;
}
#endif
struct u_dev_node * u_device_node_find_by_pathname(char *path_name) {
dlist_t *root = NULL;
u_dev_node_t *dev_node = NULL;
if (!path_name || !g_root_dev_node) {
ddkc_warn("invalid pathname[%p] or root dev node[%p]\r\n", path_name, g_root_dev_node);
return NULL;
}
root = &g_root_dev_node->node;
dlist_for_each_entry(root, dev_node, u_dev_node_t, node) {
if (!strcmp(path_name, dev_node->path_name)) {
ddkc_dbg("dev_node with pathname[%s] found\r\n", dev_node->path_name);
return dev_node;
}
}
ddkc_dbg("dev_node with pathname[%s] not found\r\n", path_name);
return NULL;
}
struct u_dev_node * u_device_node_find_by_nodename(char *node_name) {
dlist_t *root = NULL;
u_dev_node_t *dev_node = NULL;
if (!node_name || !g_root_dev_node) {
ddkc_warn("invalid node_name[%p] or root dev node[%p]\r\n", node_name, g_root_dev_node);
return NULL;
}
root = &g_root_dev_node->node;
dlist_for_each_entry(root, dev_node, u_dev_node_t, node) {
// exclude "/dev/" from dev_node->path_name
if (!strcmp(node_name, dev_node->path_name + sizeof(G_ROOT_PATH) + 1)) {
ddkc_dbg("dev_node with node_name[%s] found\r\n", dev_node->path_name);
return dev_node;
}
}
ddkc_dbg("dev_node with node_name[%s] not found\r\n", node_name);
return NULL;
}
struct u_dev_node * u_device_node_find_by_dev(struct u_device *u_dev) {
dlist_t *root = NULL;
u_dev_node_t *dev_node = NULL;
if (!u_dev || !g_root_dev_node) {
ddkc_warn("invalid dev[%p] or root dev node[%p]\r\n", u_dev, g_root_dev_node);
return NULL;
}
root = &g_dev_node_list;
dlist_for_each_entry(root, dev_node, u_dev_node_t, node) {
if (u_dev == dev_node->dev) {
ddkc_dbg("dev_node with u_dev[%p] found\r\n", u_dev);
return dev_node;
}
}
ddkc_dbg("dev_node with u_dev[%p] not found\r\n", u_dev);
return NULL;
}
int u_device_root_node_init(void) {
char *root_path = G_ROOT_PATH;
unsigned int len = sizeof(u_dev_node_t) + strlen(root_path) + 1;
dlist_init(&g_dev_node_list);
g_root_dev_node = malloc(len);
if (!g_root_dev_node) {
ddkc_err("fail to malloc for root device node\r\n");
return -ENOMEM;
}
memset(g_root_dev_node, 0, len);
dlist_init(&g_root_dev_node->node);
strncpy(g_root_dev_node->name, root_path, strlen(root_path) + 1);
g_root_dev_node->name[strlen(root_path)] = '\0';
g_root_dev_node->path_name = g_root_dev_node->name;
dlist_add(&g_root_dev_node->node, &g_dev_node_list);
ddkc_dbg("root device node initialized\r\n");
return 0;
}
/**
* delete device from system
*
* @param dev - pointer to device to be deleted
* @return 0 for success; negative for failure
*/
int u_device_del(struct u_device *dev) {
if (!dev)
return -EINVAL;
if (dev->p) {
unsigned long flags;
u_driver_t *drv = NULL;
u_device_private_t *p = dev->p;
//dlist_del(p->bus_node); /* already done in u_bus_del_device */
drv = dev->drv;
if (drv && drv->p) {
// remove drv_node from driver's device list
u_driver_private_t *drv_p = drv->p;
spin_lock_irqsave(&drv_p->lock, flags);
dlist_del(&p->drv_node);
spin_unlock_irqrestore(&drv_p->lock, flags);
}
spin_lock_irqsave(&dev->parent->p->lock, flags);
dlist_del(&p->parent_node);
// TODO: should detach all child in child_head
//dlist_del(p->child_head);
spin_unlock_irqrestore(&dev->parent->p->lock, flags);
if (p->name) {
free(p->name);
p->name = NULL;
}
free(p);
dev->p = NULL;
}
return 0;
}
/**
* unregister device from system
* @param dev - pointer to target device to be unregistered
* @return 0 for success; negative for failure
*/
int u_device_unregister(struct u_device *dev) {
return u_device_del(dev);
}
#if AOS_COMP_CLI
/**
* service handler - change log level of udevice
*
*/
static void u_device_loglevel_cmd(char *wbuf, int len, int argc, char **argv) {
if (argc < 1) {
ddkc_err("arg too short, current loglevel:%d\r\n", g_ddkc_log_level);
return;
}
switch (*argv[1]) {
case 'l':
case 'L':
g_ddkc_log_level = DDKC_LOG_LOUD;
break;
case 'd':
case 'D':
g_ddkc_log_level = DDKC_LOG_DEBUG;
break;
case 'i':
case 'I':
g_ddkc_log_level = DDKC_LOG_INFO;
break;
case 'w':
case 'W':
g_ddkc_log_level = DDKC_LOG_WARN;
break;
case 'e':
case 'E':
g_ddkc_log_level = DDKC_LOG_ERROR;
break;
default:
break;
}
ddkc_err("loglevel set to %d\r\n", g_ddkc_log_level);
return;
}
struct cli_command u_device_test_cmds[] = {
{"udev_loglevel", "adjust udevice log level", u_device_loglevel_cmd},
};
static int u_devicd_test_cmd_init(void) {
ddkc_dbg("registering udevice commands\r\n");
return aos_cli_register_commands(&u_device_test_cmds[0],
sizeof(u_device_test_cmds)/sizeof(u_device_test_cmds[0]));
}
#endif /* AOS_COMP_CLI */
int u_device_init(void) {
#if AOS_COMP_CLI
u_devicd_test_cmd_init();
#endif
return u_device_root_node_init();
}
#include "drivers/u_ld.h"
CORE_DRIVER_ENTRY(u_device_init)
| YifuLiu/AliOS-Things | components/drivers/core/base/core/u_device.c | C | apache-2.0 | 12,696 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <stddef.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "aos/list.h"
#include <drivers/spinlock.h>
#include <drivers/char/u_device.h>
#include <drivers/char/u_driver.h>
#include <drivers/char/u_bus.h>
/**
* dump driver information
*
* @param drv - pointer to target driver to be dumped
* @return 0 for success; -1 for failure
*
*/
int u_driver_dump(struct u_driver *drv) {
if (!drv) {
ddkc_err("drv is NULL\r\n");
return -1;
}
ddkc_info("drv->name:%s, drv:%p, bus:%p, p:%p\r\n",
drv->name ? drv->name : "NULL",
drv, drv->bus, drv->p);
ddkc_info("drv->init:%p, drv->deinit:%p, drv->pm:%p, drv->on_ping:%p\r\n",
drv->init, drv->deinit, drv->pm, drv->on_ping);
ddkc_info("drv->probe:%p, drv->remove:%p, drv->shutdown:%p, drv->suspend:%p, drv->resume:%p\r\n",
drv->probe, drv->remove, drv->shutdown, drv->suspend, drv->resume);
return 0;
}
/**
* check whether driver with the same name is already loaded or not
* check whether driver with same name is already registered or not
*
* @param drv - pointer to target driver to be found
* @return 0 for success; -1 for failure
*/
int _bus_find_driver(struct u_driver *drv) {
u_bus_t *bus = drv->bus;
u_driver_private_t *drv_p = NULL;
struct dlist_s *next = NULL;
u_driver_t *drv_b = NULL;
dlist_for_each_entry_safe(&bus->p->drv_list, next, drv_p, u_driver_private_t, bus_node) {
drv_b = drv_p->drv;
if (!strcmp(drv->name, drv_b->name))
return 1;
}
return 0;
}
/**
* driver private struct initialization
* @param drv - pointer to target driver
* @return 0 for success; negative for failure
*/
int u_driver_initialize(struct u_driver *drv) {
u_driver_private_t *p = NULL;
p = (u_driver_private_t *)malloc(sizeof(u_driver_private_t));
if (!p) {
ddkc_err("malloc for u_driver_private_t fails\r\n");
return -ENOMEM;
}
ddkc_dbg("malloc for u_driver_private_t done\r\n");
spin_lock_init(&p->lock);
dlist_init(&p->dev_list);
dlist_init(&p->bus_node);
p->drv = drv;
drv->p = p;
return 0;
}
/**
* free driver's private struct
*
* @param drv - pointer to target driver
* @return always return 0
*/
int u_driver_deinitialize(struct u_driver *drv) {
free(drv->p);
drv->p = NULL;
return 0;
}
/**
* add drvier into system
*
* @param drv - pointer to target driver
* @return 0 for success; negative for failure
*/
int u_driver_add(struct u_driver *drv) {
int r = 0;
// TODO: need to assign drv->bus to platform_bus if it is not assigned
if (!drv->p || !drv->bus || !drv->name) {
ddkc_err("invalid drv->p:%p, drv->bus:%p or drv->name:%p\r\n", drv->p, drv->bus, drv->name);
return -EINVAL;
}
r = _bus_find_driver(drv);
if (r) {
ddkc_err("drv[%s] is already added\r\n", drv->name);
return -EBUSY;
}
r = u_bus_add_driver(drv);
if (r)
goto drv_add_error;
u_bus_attach_driver(drv);
return 0;
drv_add_error:
free(drv->p);
drv->p = NULL;
return -1;
}
/**
* delete driver from system
* detach it from bus and ehen delete the driver from bus
*
* @param drv - pointer to target driver
* @return 0 for success; negative for failure
*/
int u_driver_del(struct u_driver *drv) {
int r = 0;
/* deinit devices attached to this driver before delete it from bus */
r = u_bus_detach_driver(drv);
if (r)
ddkc_err("detach drv[%s] failed, r:%d\r\n", drv->name, r);
r = u_bus_del_driver(drv);
if (r)
ddkc_err("delete drv[%s] failed, r:%d\r\n", drv->name, r);
return r;
}
/**
* register a driver into system, init it's private struct before add it into system
*
* @param drv - pointer to target driver to be registered
* @return 0 for success; negative for failure
*/
int u_driver_register(struct u_driver *drv) {
if(!drv)
return -EINVAL;
u_driver_initialize(drv);
return u_driver_add(drv);
}
/**
* unregister a driver from system
* delete it and then free its private struct
*
* @param drv - pointer to target driver to be registered
* @return 0 for success; negative for failure
*/
int u_driver_unregister(struct u_driver *drv) {
if(!drv)
return -EINVAL;
u_driver_del(drv);
return u_driver_deinitialize(drv);
}
| YifuLiu/AliOS-Things | components/drivers/core/base/core/u_driver.c | C | apache-2.0 | 4,241 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <errno.h>
#include <pthread.h>
#include "aos/list.h"
#include <drivers/bug.h>
#include <drivers/compat.h>
#include <drivers/char/u_device.h>
#include <drivers/u_interrupt.h>
//TODO: use rbtree instead
#if U_IRQ_DESC_LIST_RBTREE
#else
dlist_t g_u_irq_thread_head;
dlist_t g_u_irq_desc_head;
u_irq_lock_t g_u_irq_lock;
u_irq_desc_t g_dummy_irq = {.name = "dummy",
.irq_id = 0xFEDC,
.irq_handler = NULL,
.thread_handler = NULL,
.irq_cnt = 0,
.flags = 0,
.data = &g_dummy_irq,
.p_irq_th = NULL,
};
#endif
#if U_IRQ_LOCK_SPINLOCK
static inline int u_irq_lock_init(u_irq_lock_t *lock) {
int ret = -1;
ret = pthread_spin_init(lock, PTHREAD_PROCESS_PRIVATE);
if (ret) {
ddkc_err("pthread_spin_init failed, ret:%d\r\n", ret);
} else {
ddkc_dbg("pthread_spin_init success\r\n");
}
return ret;
}
static inline int u_irq_lock_lock(u_irq_lock_t *lock) {
int ret = -1;
ret = pthread_spin_lock(lock);
if (ret) {
ddkc_err("pthread_spin_lock failed, ret:%d\r\n", ret);
} else {
ddkc_dbg("pthread_spin_lock success\r\n");
}
return ret;
}
static inline int u_irq_lock_unlock(u_irq_lock_t *lock) {
int ret = -1;
ret = pthread_spin_unlock(lock);
if (ret) {
ddkc_err("pthread_spin_unlock failed, ret:%d\r\n", ret);
} else {
ddkc_dbg("pthread_spin_unlock success\r\n");
}
return ret;
}
static inline int u_irq_lock_destroy(u_irq_lock_t *lock) {
int ret = -1;
ret = pthread_spin_destroy(lock);
if (ret) {
ddkc_err("pthread_spin_destroy failed, ret:%d\r\n", ret);
} else {
ddkc_dbg("pthread_spin_destroy success\r\n");
}
return ret;
}
#else
static inline int u_irq_lock_init(u_irq_lock_t *lock) {
int ret = -1;
ret = pthread_mutex_init(lock, NULL);
if (ret) {
ddkc_err("pthread_mutex_init failed, ret:%d\r\n", ret);
} else {
ddkc_loud("pthread_mutex_init success\r\n");
}
return ret;
}
static inline int u_irq_lock_lock(u_irq_lock_t *lock) {
int ret = -1;
ret = pthread_mutex_lock(lock);
if (ret) {
ddkc_err("pthread_mutex_lock failed, ret:%d\r\n", ret);
} else {
ddkc_loud("pthread_mutex_lock success\r\n");
}
return ret;
}
static inline int u_irq_lock_unlock(u_irq_lock_t *lock) {
int ret = -1;
ret = pthread_mutex_unlock(lock);
if (ret) {
ddkc_err("pthread_mutex_unlock failed, ret:%d\r\n", ret);
} else {
ddkc_loud("pthread_mutex_unlock success\r\n");
}
return ret;
}
static inline int u_irq_lock_destroy(u_irq_lock_t *lock) {
int ret = -1;
ret = pthread_mutex_destroy(lock);
if (ret) {
ddkc_err("pthread_mutex_destroy failed, ret:%d\r\n", ret);
} else {
ddkc_loud("pthread_mutex_destroy success\r\n");
}
return ret;
}
#endif
u_irqreturn_t u_irq_handler(int irq_id, void *data) {
u_irq_desc_t *tmp = NULL;
u_irq_desc_t *desc = (u_irq_desc_t *)data;
u_irq_thread_t *p_irq_th = NULL;
u_irq_msg_t *p_irq_msg = NULL;
#if 0
p_irq_th = desc->p_irq_th;
p_irq_msg = (u_irq_msg_t *)malloc(sizeof(*p_irq_msg));
if (p_irq_msg) {
p_irq_msg->u_irq = desc;
u_irq_lock_lock(&p_irq_th->lock);
dlist_add_tail(&p_irq_msg->node, &p_irq_th->msg_head);
u_irq_lock_unlock(&p_irq_th->lock);
pthread_cond_signal(&p_irq_th->cond);
} else {
ddkc_err("malloc for irq_msg failed, %d missed\n", irq_id);
}
#else
// search irq_id's thread
dlist_for_each_entry_safe(&g_u_irq_desc_head, tmp, desc, u_irq_desc_t, irq_desc_node) {
if (desc->irq_id != irq_id)
continue;
p_irq_th = desc->p_irq_th;
// TODO: malloc is not allowed in IRQ context
// add irq_id into p_irq_th's message list
p_irq_msg = (u_irq_msg_t *)malloc(sizeof(*p_irq_msg));
if (p_irq_msg) {
p_irq_msg->u_irq = desc;
u_irq_lock_lock(&p_irq_th->lock);
dlist_add_tail(&p_irq_msg->node, &p_irq_th->msg_head);
u_irq_lock_unlock(&p_irq_th->lock);
pthread_cond_signal(&p_irq_th->cond);
} else {
ddkc_err("malloc for irq_msg failed, %d missed\r\n", irq_id);
}
}
#endif
return IRQ_HANDLED;
}
void* u_irq_thread_fn(void *arg) {
unsigned int r = -1;
u_irq_thread_t *p_irq_th = (u_irq_thread_t *)arg;
u_irq_msg_t *tmp = NULL;
u_irq_msg_t *p_irq_msg = NULL, *next = NULL;
u_irq_desc_t *desc = NULL;
BUG_ON(!p_irq_th);
do {
dlist_for_each_entry_safe(&p_irq_th->msg_head, tmp, p_irq_msg, u_irq_msg_t, node) {
u_irq_msg_t *m = p_irq_msg;
//TODO: NOTICE performance issue!!!
/** shall we add another lock to protect this critical section from operation on desc in u_free_irq?
*/
u_irq_lock_lock(&p_irq_th->lock);
dlist_del(p_irq_msg);
desc = m->u_irq;
if (desc->thread_handler)
(desc->thread_handler)(desc->irq_id, desc->data);
else if (desc->irq_handler)
(desc->irq_handler)(desc->irq_id, desc->data);
desc->irq_cnt++;
u_irq_lock_unlock(&p_irq_th->lock);
free(p_irq_msg);
//TODO: shall add monitor on irq_cnt in <x> ms, disable the irq for flood irq case
}
r = pthread_cond_wait(&p_irq_th->cond, &p_irq_th->mutex);
if (r) {
ddkc_err("%s wait for cond failed, r:%d\r\n", p_irq_th->name, r);
}
} while (!p_irq_th->should_stop);
//TODO: clear IRQ related resources
p_irq_th->stopped = 1;
ddkc_info("thread %p stopped\r\n", p_irq_th);
return NULL;
}
u_irq_thread_t *u_irq_thread_create(u_irq_desc_t *u_irq, int prio) {
int r = -1;
u_irq_thread_t *p_irq_th = NULL;
pthread_attr_t attr;
if (!u_irq) {
ddkc_err("invalid p_irq_th or u_irq\r\n");
return NULL;
}
p_irq_th = (u_irq_thread_t *)malloc(sizeof(*p_irq_th));
if (!p_irq_th) {
ddkc_err("malloc u_irq_thread_t for irq-%d failed\r\n", u_irq->irq_id);
return NULL;
}
p_irq_th->should_stop = 0;
p_irq_th->stopped = 0;
dlist_init(&p_irq_th->irq_desc_head);
dlist_init(&p_irq_th->irq_thread_node);
dlist_init(&p_irq_th->msg_head);
pthread_condattr_init(&p_irq_th->condattr);
pthread_condattr_setclock(&p_irq_th->condattr, CLOCK_MONOTONIC);
pthread_cond_init(&p_irq_th->cond, &p_irq_th->condattr);
pthread_mutex_init(&p_irq_th->mutex, NULL);
u_irq_lock_init(&p_irq_th->lock);
pthread_attr_init(&attr);
#if 0 //TODO: need to adjust thread's priority!!, change 0 and 120 to marco
struct sched_param sched;
if (prio <= 0 && prio > 120)
sched.sched_priority = 1;
else
sched.sched_priority = prio;
pthread_attr_setschedparam(&attr,&sched);
pthread_attr_setstacksize(&attr,4096);
#endif
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
r = pthread_create(&(p_irq_th->thread), &attr, u_irq_thread_fn, (void*)(p_irq_th));
pthread_attr_destroy(&attr);
if(!r) {
memset(p_irq_th->name, 0, sizeof(p_irq_th->name));
if (u_irq != &g_dummy_irq)
snprintf(p_irq_th->name, sizeof(p_irq_th->name), "irq-%d", u_irq->irq_id);
else
snprintf(p_irq_th->name, sizeof(p_irq_th->name), "irq-m-%d", getpid());
// assume this operation won't fail
pthread_setname_np(p_irq_th->thread, p_irq_th->name);
} else {
ddkc_err("pthread_create for irq-%d failed, r:%d\r\n", u_irq->irq_id, r);
free(p_irq_th);
return NULL;
}
ddkc_info("pthread create for irq-%d success, pid:%p, name:%s\r\n",
u_irq->irq_id, p_irq_th->thread, p_irq_th->name);
// add irq's thread_node into thread's irq_desc_head
u_irq_lock_lock(&p_irq_th->lock);
dlist_add_tail(&u_irq->thread_node, &p_irq_th->irq_desc_head);
u_irq_lock_unlock(&p_irq_th->lock);
u_irq_lock_lock(&g_u_irq_lock);
dlist_add_tail(&p_irq_th->irq_thread_node, &g_u_irq_thread_head);
u_irq_lock_unlock(&g_u_irq_lock);
return p_irq_th;
}
int u_irq_thread_delete(u_irq_thread_t *t) {
t->should_stop = 1;
pthread_cond_signal(&t->cond);
/* wait for thread to quit and free the thread if necessary */
while(!t->stopped) {
// TODO: ethan - should add sychnronized mechanism
//msleep(50);
usleep(50 * 1000);
}
u_irq_lock_lock(&g_u_irq_lock);
dlist_del(&t->irq_thread_node);
u_irq_lock_unlock(&g_u_irq_lock);
WARN_ON(!dlist_empty(&t->irq_desc_head));
pthread_cond_destroy(&t->cond);
pthread_mutex_destroy(&t->mutex);
u_irq_lock_destroy(&t->lock);
pthread_condattr_destroy(&t->condattr);
free(t);
return 0;
}
//TODO:- must be called before any other IRQ system APIs called
int u_irq_system_init(void) {
int r = 0;
u_irq_thread_t *g_u_irq_th = NULL;
dlist_init(&g_u_irq_thread_head);
dlist_init(&g_u_irq_desc_head);
u_irq_lock_init(&g_u_irq_lock);
g_u_irq_th = u_irq_thread_create(&g_dummy_irq, -1);
if (g_u_irq_th) {
ddkc_info("u_irq system init success\r\n");
r = 0;
} else {
ddkc_err("u_irq_thread_create for g_dummy_irq failed\r\n");
return -ENOMEM;
}
g_dummy_irq.p_irq_th = g_u_irq_th;
u_irq_lock_lock(&g_u_irq_lock);
dlist_add_tail(&g_dummy_irq.irq_desc_node, &g_u_irq_desc_head);
u_irq_lock_unlock(&g_u_irq_lock);
return r;
}
int u_irq_system_deinit(void) {
u_irq_desc_t *desc = NULL;
u_irq_desc_t *n = NULL;
// search irq_id's thread
dlist_for_each_entry_safe(&g_u_irq_desc_head, n, desc, u_irq_desc_t, irq_desc_node) {
if (desc == &g_dummy_irq)
continue;
// deattch irq desc from g_u_irq_desc_head
u_irq_lock_lock(&g_u_irq_lock);
dlist_del(&desc->irq_desc_node);
u_irq_lock_unlock(&g_u_irq_lock);
// remove irq desc
u_irq_remove(desc);
free(desc);
}
// remove irq desc
u_irq_remove(desc);
return 0;
}
int u_irq_setup(u_irq_desc_t *u_irq) {
if (!u_irq)
return -EINVAL;
BUG_ON_MSG((g_dummy_irq.irq_id == u_irq->irq_id),
"u_irq->irq_id equals with dummy irq_id, should NEVER happen\n");
if (u_irq->thread_handler) {
u_irq_thread_t *u_irq_th = u_irq_thread_create(u_irq, -1);
if (!u_irq_th)
return -ENOMEM;
u_irq->p_irq_th = u_irq_th;
} else if (u_irq->irq_handler) {
u_irq->p_irq_th = g_dummy_irq.p_irq_th;
} else {
ddkc_err("!!!!This should never happen\r\n");
return -EINVAL;
}
// add irq_desc_node to global u_irq_desc list
u_irq_lock_lock(&g_u_irq_lock);
dlist_add_tail(&u_irq->irq_desc_node, &g_u_irq_desc_head);
u_irq_lock_unlock(&g_u_irq_lock);
/** TODO: call system API to register IRQ
* Passthrough mode: register u_irq->irq_handler directly to low level system
* Agent mode: register agent irq handler (u_irq_handler) to system
*/
return 0;
}
int u_irq_remove(u_irq_desc_t *u_irq) {
int ret = 0;
u_irq_thread_t *p_irq_th = NULL;
if (!u_irq) {
ddkc_err("invalid u_irq:%p\r\n", u_irq);
return -EINVAL;
}
if (!u_irq->p_irq_th || !u_irq->thread_handler) {
ddkc_dbg("irq:%d pthread_irq_th:%p, thread_handler:%p, no need to stop irq thread\r\n",
u_irq->irq_id, u_irq->p_irq_th, u_irq->thread_handler);
return 0;
}
ddkc_dbg("start to clear resource for irq:%d\r\n", u_irq->irq_id);
p_irq_th = u_irq->p_irq_th;
if ((p_irq_th == g_dummy_irq.p_irq_th) &&
(u_irq->irq_id != g_dummy_irq.irq_id)) {
ddkc_info("irq[%d] shares common irq thread, ignore\r\n", u_irq->irq_id);
return 0;
}
ret = u_irq_thread_delete(p_irq_th);
ddkc_dbg("thread stopped for irq:%d\r\n", u_irq->irq_id);
return 0;
}
int u_request_threaded_irq(
unsigned int irq, u_irq_handler_t handler, u_irq_handler_t thread_fn,
unsigned long flags, const char *name, void *data) {
int r = -1;
u_irq_desc_t *u_irq = NULL;
if (!handler && !thread_fn) {
ddkc_err("both handler and thread_fn is NULL\r\n", irq);
return -EINVAL;
}
u_irq = (u_irq_desc_t *)malloc (sizeof(u_irq_desc_t));
if (!u_irq) {
ddkc_err("malloc u_irq_desc_t failed for irq:%d\r\n", irq);
return -ENOMEM;
}
#if U_IRQ_DESC_LIST_RBTREE
#else
dlist_init(&u_irq->irq_desc_node);
#endif
dlist_init(&u_irq->thread_node);
u_irq->name = name;
u_irq->data = data;
u_irq->flags = flags;
u_irq->irq_cnt = 0;
u_irq->irq_id = irq;
u_irq->irq_handler = handler;
u_irq->thread_handler = thread_fn;
u_irq->p_irq_th = NULL;
/* setup new thread if needed */
r = u_irq_setup(u_irq);
if (r)
goto irq_setup_fail;
return 0;
irq_setup_fail:
u_irq_remove(u_irq);
free(u_irq);
return r;
}
void free_u_irq(unsigned int irq_id) {
u_irq_desc_t *n = NULL;
u_irq_desc_t *u_irq = NULL;
u_irq_thread_t *p_irq_th = NULL;
u_irq_msg_t *p_irq_msg = NULL, *next = NULL;
// search irq_id's thread
dlist_for_each_entry_safe(&g_u_irq_desc_head, n, u_irq, u_irq_desc_t, irq_desc_node) {
if (u_irq->irq_id != irq_id)
continue;
p_irq_th = u_irq->p_irq_th;
dlist_for_each_entry_safe(&p_irq_th->msg_head, next, p_irq_msg, u_irq_msg_t, node) {
// clear all irq message of target irq
if (p_irq_msg->u_irq == u_irq) {
u_irq_lock_lock(&p_irq_th->lock);
dlist_del(p_irq_msg);
u_irq_lock_unlock(&p_irq_th->lock);
free(p_irq_msg);
}
}
// deattach u_irq from thread's irq list and global irq desc list
u_irq_lock_lock(&p_irq_th->lock);
dlist_del(&u_irq->thread_node);
u_irq_lock_unlock(&p_irq_th->lock);
u_irq_lock_lock(&g_u_irq_lock);
dlist_del(&u_irq->irq_desc_node);
u_irq_lock_unlock(&g_u_irq_lock);
// try to clean irq's thread resource
u_irq_remove(u_irq);
free(u_irq);
}
return 0;
}
void disable_u_irq_nosync(unsigned int irq) {
}
void disable_u_irq(unsigned int irq) {
}
void enable_u_irq(unsigned int irq) {
}
__weak void free_irq(unsigned int irq, void *dev_id) {
}
void __wrap_free_irq(unsigned int irq, void *dev_id) {
__real_free_irq(irq, dev_id);
}
| YifuLiu/AliOS-Things | components/drivers/core/base/core/u_interrupt.c | C | apache-2.0 | 13,226 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#if defined(USER_SPACE_DRIVER) && defined(ENABLE_IO_MMAP)
#include <iomap.h>
#endif
#include <drivers/u_ld.h>
/**
* unified driver initialization entry
* do register map prior to call driver's init entry in user space
*
* @param drv_name - driver's name
* @param drv_init_entry - pointer to driver's init entry
* @param get_hw_info - pointer to the function to get driver's register info
* @return 0 for success; negative for failure
*
*/
int _unify_driver_init(const char *drv_name, OS_DRIVER_ENTRY drv_init_entry, DEVICE_HW_REG_INFO get_hw_info) {
TRACE_DRV_ENTRY();
#if defined(USER_SPACE_DRIVER) && defined(ENABLE_IO_MMAP)
/* this part is necessary only when the driver is in user space */
if (get_hw_info) {
hw_reg_array_info_t *info = (get_hw_info)();
/* if driver's hw register info is not 0, do memory map on these register/length array one by one */
if (info && info->size) {
int i = 0;
int j = 0;
int ret = 0;
hw_reg_info_t *p_reg_info = NULL;
printf("%s: get_hw_info: size:%d, hw:%p\r\n", drv_name, info->size, info->hw);
for (i = 0; i < info->size; i++) {
p_reg_info = (info->hw[0] + i);
if (!p_reg_info || !p_reg_info->addr || !p_reg_info->length) {
ret = -EINVAL;
goto err;
}
printf("%s: i:%d, p_reg_info:%p, addr:0x%lx, length:%d\r\n",
drv_name, i, p_reg_info, p_reg_info->addr, p_reg_info->length);
ret = aos_io_mmap(p_reg_info->addr, p_reg_info->addr, p_reg_info->length);
printf("%s: aos_io_mmap on [%lx,0x%ld] return %d\r\n",
drv_name, p_reg_info->addr, p_reg_info->addr, ret);
if (!ret)
continue;
err:
printf("%s: hw_reg_array_info_t error, size:%d, invalid hw[%d]:%p\r\n",
drv_name, info->size, i, info->hw[i]);
// unmap the driver if do memory map fails
for (j = 0; j < i; j++) {
p_reg_info = info->hw[j];
aos_io_unmmap(p_reg_info->addr);
}
printf("%s: map hw register failed, ignore %s\r\n", drv_name, drv_name);
return ret;
}
}
}
#endif
/* do driver initialization */
return (drv_init_entry)();
}
| YifuLiu/AliOS-Things | components/drivers/core/base/core/u_ld.c | C | apache-2.0 | 2,616 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifdef USER_SPACE_DRIVER
#include <rpc.h>
#endif
#include "aos/vfs.h"
#include "aos/list.h"
#include <devicevfs/devicevfs.h>
#include <drivers/char/u_cdev_msg.h>
#include <drivers/u_mode.h>
#define MAJOR_OFFSET 120
#define NODE_PREFIX "/dev/"
static dlist_t g_fnode_valid_list;
static dlist_t g_subsys_dev_list;
typedef struct file_node {
file_t f; // created when OPEN RPC request arrives
void *dev_n;
dlist_t node;
dlist_t valid;
} file_node_t;
typedef struct subsys_dev_node {
dlist_t n;
struct subsys_dev dev;
struct u_platform_device *pdev;
struct u_platform_driver *pdrv;
subsys_file_ops_t *fops;
dlist_t file_head;
int rpc_handle;
int ref_cnt;
bool rpc_run;
char *rpc_name;
char *path_name;
/* real_open was used only when delay_init, which is member of struct subsys_dev, is set to true */
int (*real_open)(inode_t *node, file_t *fp);
int (*real_init)(struct u_platform_device *pdev);
int (*real_probe)(struct u_platform_device *pdev);
} subsys_dev_node_t;
#ifdef USER_SPACE_DRIVER
#define UDRIVER_RCP_NAME_MAX_LEN (AOS_RPC_NAME_MAX_SIZE)
#define UDRIVER_RPC_NAME_FORMAT "rpc-%d-%s"
extern char *u_driver_get_main_service_name(void);
static int _cdev_fops_handler(int crpc_handle, u_cdev_msg_t *p_msg);
static int _loop_msg_handler(int crpc_handle, u_cdev_msg_t *p_msg);
static u_cdev_msg_handler _cdev_msg_handler[CDEV_MSG_MAX] = {
[CDEV_MSG_FOPS] = _cdev_fops_handler,
[CDEV_MSG_LOOP] = _loop_msg_handler,
};
/**
* check whether fnode is valid or not
* to prevent client send invalid RPC request with cached data
*
* @param fnode - pointer to target file_node_t
* @return true if it is valid; false if it is invalid
*/
static bool _is_valid_fnode(file_node_t *fnode) {
file_node_t *n = NULL;
dlist_t *pos = NULL;
dlist_t *tmp = NULL;
dlist_for_each_safe(pos, tmp, &g_fnode_valid_list)
{
n = aos_container_of(pos, file_node_t, valid);
if (n == fnode)
return true;
}
return false;
}
/**
* char device file operation handler
*
* @param crpc_handle - RPC client's handle
* @param p_msg - pointer to operation struct
*
* @return 0 for success; negative for failure
*/
int _cdev_fops_handler(int crpc_handle, u_cdev_msg_t *p_msg) {
int ret = 0;
u_cdev_msg_ie_t *ie = NULL;
struct subsys_dev_node *dev_n = NULL;
subsys_file_ops_t *fops = NULL;
u_fops_arg_u *fops_arg = NULL;
file_t *fp = NULL;
file_node_t *fnode = NULL;
inode_t *node = NULL;
u_fops_result_u res;
if (!p_msg) {
return -EINVAL;
}
ie = p_msg->v;
fops_arg = (u_fops_arg_u *)ie->v;
/* fnode is put into open.farg in u_device_rpc_open */
fnode = (file_node_t *)fops_arg->priv.farg;
ddkc_dbg("farg:%p\r\n", fnode);
if (!fnode) {
ret = -EINVAL;
ddkc_err("fops_arg->priv.arg is NULL, ignore\r\n");
goto err;
}
// do fnode's validation
if (!_is_valid_fnode(fnode)) {
// this case should NEVER happen, so omit this check
BUG_ON_MSG(1, "invalid fnode:%p from rpc client:0x%x\r\n", fnode, crpc_handle);
return -EINVAL;
}
dev_n = fnode->dev_n;
if (ie->t <= FOPS_OPEN || ie->t >= FOPS_MAX) {
ret = -EINVAL;
ddkc_err("invalid file operation:%d, ignore, ret:%d\r\n", ie->t, ret);
goto err;
}
memset(&res, 0, sizeof(res));
fp = &fnode->f;
node = fp->node;
fops = (subsys_file_ops_t *)node->ops.i_ops;
switch(ie->t) {
case FOPS_READ:
{
ssize_t r_len = 0;
u_fops_result_u *p_res = malloc(sizeof(*p_res) + fops_arg->read.len);
if (!p_res) {
ddkc_err("%s - malloc for u_fops_result_u failed\r\n", dev_n->rpc_name);
ret = -ENOMEM;
goto err;
}
memset(p_res, 0, sizeof(*p_res) + fops_arg->read.len);
/* call device's read cb */
r_len = fops->read(fp, p_res->read.data, fops_arg->read.len);
if (r_len < 0) {
ret = r_len;
ddkc_warn("fops->read ret:%d\r\n", r_len);
free(p_res);
goto err;
}
p_res->read.status = 0;
p_res->read.len = r_len;
ddkc_dbg("FOPS_READ, status:%d, len:%d, total len:%d, sizeof(u_fops_result_u):%d\r\n",
p_res->priv.status, p_res->read.len, sizeof(*p_res) + r_len, sizeof(u_fops_result_u));
#if 0
for (int i = 0; i < sizeof(*p_res) + r_len; i++) {
ddkc_info("%d - 0x%x\r\n", i, *((char *)p_res + i) & 0xff);
}
#endif
ret = aos_rpc_resp(crpc_handle, 1, sizeof(*p_res) + r_len, p_res);
if (ret)
ddkc_err("%s - aos_rpc_resp to 0x%x failed, ret:0x%x\r\n", dev_n->rpc_name, crpc_handle, ret);
free(p_res);
return ret;
}
break;
case FOPS_WRITE:
{
ssize_t w_len = 0;
ddkc_dbg("%s - fops->write++\r\n", __func__);
/* call device's write cb */
w_len = fops->write(fp, fops_arg->write.buf, fops_arg->write.len);
if (w_len < 0) {
ret = w_len;
ddkc_warn("%s - fops->write ret:%d\r\n", dev_n->rpc_name, w_len);
goto err;
}
res.write.status = 0;
res.write.len = w_len;
ddkc_dbg("FOPS_WRITE, status:%d, len:%d\r\n", res.write.status, res.write.len);
}
break;
case FOPS_IOCTL:
/* call device's ioctl cb */
ret = fops->ioctl(fp, fops_arg->ioctl.cmd, fops_arg->ioctl.arg);
if (ret < 0) {
ddkc_warn("%s - fops->ioctl ret:%d\r\n", dev_n->rpc_name, ret);
goto err;
}
res.ioctl.status = ret;
ddkc_dbg("FOPS_IOCTL, status:%d\r\n", res.ioctl.status);
break;
case FOPS_POLL:
//TODO: to be implemented
ret = -EIO;
res.poll.status = ret;
ddkc_err("%s - poll ops is not implemented,ret:%d\r\n", dev_n->rpc_name, ret);
break;
case FOPS_LSEEK:
/* call device's lseek cb */
ret = fops->lseek(fp, fops_arg->lseek.off, fops_arg->lseek.whence);
if (ret < 0) {
ddkc_warn("%s - fops->seek ret:%d\r\n", dev_n->rpc_name, ret);
}
res.lseek.off = ret;
res.lseek.status = 0;
ddkc_dbg("FOPS_LSEEK, status:%d, offset:%lld\r\n", res.lseek.status, res.lseek.off);
break;
case FOPS_CLOSE:
// close is not handled here, it is handled in main rpc thread
ret = -EIO;
res.close.status = ret;
ddkc_err("%s - close ops is not implemented,ret:%d\r\n", dev_n->rpc_name, ret);
break;
default:
ret = -EINVAL;
res.priv.status = ret;
ddkc_err("%s - fops invalid ops id:%d\r\n", dev_n->rpc_name, ie->t);
break;
}
/* send response back to rpc client
* no matter actual read/write/ioctl/poll/select is done or not, response is necessary
* */
ret = aos_rpc_resp(crpc_handle, 1, sizeof(res), &res);
if (ret)
ddkc_err("%s - aos_rpc_resp to 0x%x failed, ret:0x%x\r\n", dev_n->rpc_name, crpc_handle, ret);
return ret;
err:
/* send error indication back to rpc client */
res.priv.status = ret;
ret = aos_rpc_resp(crpc_handle, 1, sizeof(res), &res);
if (ret)
ddkc_err("aos_rpc_resp to 0x%x failed, ret:0x%x\r\n", crpc_handle, ret);
return ret;
}
/**
* heartbeat message handler - for rpc service active detection
*
* @param crpc_handle - remote client's rpc handle
* @param p_msg - pointer to the message
* @return
*/
int _loop_msg_handler(int crpc_handle, u_cdev_msg_t *p_msg) {
int ret = 0;
ret = aos_rpc_resp(crpc_handle, 1, 1, -1);
if (ret) {
ddkc_warn("loop msg handler aos_rpc_resp failed, ret:%d\r\n", ret);
}
ddkc_warn("loop msg handler is not implemented yet\r\n");
return 0;
}
/**
* device rpc message handler
* get remote rpc client's handle and receive all contents in this RPC transaction
* parse the contents' pointer to _cdev_msg_handler for message dispatch
*
* @param pkt - rpc message packet
*/
void u_device_rpc_msg_arrived(struct aos_parcel_t *pkt) {
int ret = 0;
size_t len = 0;
int reply_handle = 0;
char *buf = NULL;
u_cdev_msg_t *p_msg = NULL;
ddkc_dbg("rpc pkt arrived\r\n");
if (!pkt || !pkt->max_size) {
ddkc_err("invalid pkt:%p or max_size:%d\r\n", pkt, pkt ? pkt->max_size : 0);
return;
}
len = sizeof(int);
ddkc_dbg("pkt->max_size:%x\r\n", pkt->max_size);
aos_parcel_get(AP_UVARINT, &reply_handle, &len, pkt);
ddkc_dbg("reply_handle:%x\r\n", reply_handle);
len = pkt->max_size;
ddkc_dbg("max_size:%x\r\n", len);
buf = malloc(len);
if (!buf) {
ddkc_err("malloc buf for rpc msg failed\r\n");
return;
}
/* get RPC message's content in one RPC call with AP_ALL flag */
ret = aos_parcel_get(AP_ALL, buf, &len, pkt);
if (ret < 0 || len <= 0) {
ddkc_err("rpc receive data failed, ret:%d\r\n", ret);
// TODO: ethan - how to handle this case?
free(buf);
return;
}
p_msg = (u_cdev_msg_t *)buf;
if (p_msg->t >= CDEV_MSG_MAX) {
for (int i = 0; i < len; i++) {
ddkc_info("%d - 0x%x\r\n", i, buf[i] & 0xff);
}
}
BUG_ON_MSG((p_msg->t >= CDEV_MSG_MAX),
"p_msg->t:%d > CDEV_MSG_MAX:%d\r\n", p_msg->t, CDEV_MSG_MAX);
if (p_msg->t < CDEV_MSG_MAX)
/* parse rpc message into _cdev_msg_handler for message dispatch */
ret = (_cdev_msg_handler[p_msg->t](reply_handle, p_msg));
else {
u_fops_result_u res;
res.priv.status = -EINVAL;
ret = aos_rpc_resp(reply_handle, 1, sizeof(res), &res);
if (ret)
ddkc_err("aos_rpc_resp to 0x%x failed, ret:0x%x\r\n", reply_handle, ret);
}
free(buf);
buf = NULL;
return;
}
/**
* rpc service event handler
* @param eid - error id, RPC_EID_STOP is rpc service stopped event id
* @param event - pointer to aos_revt_param_t
*/
void u_device_rpc_event_cb(int eid, void * event) {
struct aos_revt_param_t *param = (struct aos_revt_param_t *)event;
int reason = *(int *)param->param;
if (eid != RPC_EID_STOP) {
ddkc_warn("eid:%d, reason:%d, closing rpc service - handle:0x%x\r\n", eid, reason, param->srpc_handle);
aos_rpc_close(param->srpc_handle);
} else
ddkc_dbg("eid:%d, reason:%d\r\n", eid, reason);
return;
}
/**
*
* open RPC message handler, called when OPEN rpc message arrived in main rpc service's handler
*
* @param parg - pointer to u_fops_arg_u
* @param crpc_handle - rpc client's handle,
* response should be send to rpc client no matter this operation succeed or not
*
* @return 0 for success; negative for failure
*/
int u_device_rpc_open(u_fops_arg_u *parg, int crpc_handle) {
int ret = 0;
int flag = 0;
dlist_t *pos = NULL;
dlist_t *tmp = NULL;
file_t *fp = NULL;
inode_t *node = NULL;
file_node_t *fnode = NULL;
struct subsys_dev_node *dev_n = NULL;
subsys_file_ops_t *fops = NULL;
u_fops_result_u res;
char *path_name = NULL;
if (!parg || !crpc_handle) {
ddkc_err("invalid rpc handle:%d or parg:%p\r\n", crpc_handle, parg);
ret = -EINVAL;
goto err;
}
memset(&res, 0, sizeof(res));
// MUST call aos_rpc_resp to send RPC reply to client, no matter open success or fail
path_name = parg->open.path;
flag = parg->open.flags;
// search target device in g_subsys_dev_list
dlist_for_each_safe(pos, tmp, &g_subsys_dev_list)
{
dev_n = aos_container_of(pos, subsys_dev_node_t, n);
if (!strcmp(dev_n->path_name, path_name))
break;
dev_n = NULL;
}
if (!dev_n) {
ddkc_err("device node not found for %s\r\n", path_name);
ret = -ENODEV;
goto err;
}
ddkc_dbg("device node:%p found for %s\r\n", dev_n, path_name);
if (!dlist_empty(&dev_n->file_head)) {
ddkc_warn("device node:%s is already opened\r\n", path_name);
// concurrent operation by multiple processes is handled here
// concurrent operation by multiple threads in single process is handled in VFS
}
ddkc_dbg("setting up for new fd\r\n");
// set up new fd for each open RPC request to cover concurrent multiple open operation scenarios
fnode = malloc(sizeof(file_node_t));
node = malloc(sizeof(inode_t));
if (!fnode || !node) {
ddkc_err("malloc for file failed, fnode:%p, node:%p\n", fnode, node);
ret = -ENOMEM;
goto err;
}
dlist_init(&fnode->node);
dlist_init(&fnode->valid);
fnode->dev_n = NULL;
fp = &fnode->f;
memset(fp, 0, sizeof(file_t));
memset(node, 0, sizeof(inode_t));
fp->node = node;
node->i_arg = dev_n->dev.user_data;
node->i_name = dev_n->path_name;
node->ops.i_ops = dev_n->fops;
node->i_flags = flag;
fops = (subsys_file_ops_t *)node->ops.i_ops;
if (!fops || !(fops->open)) {
ddkc_err("invalid fops:%p, or open:%p\n", fops, fops ? fops->open : NULL);
goto err;
}
/* rpc service for device node might be started already */
if (!dev_n->rpc_run) {
ddkc_info("start rpc service named:%s, handle:0x%x\r\n", dev_n->rpc_name, dev_n->rpc_handle);
ret = aos_rpc_run(dev_n->rpc_handle, u_device_rpc_msg_arrived, u_device_rpc_event_cb);
if (ret) {
ddkc_err("aos_rpc_run on service:%s fails, ret:%d\r\n", dev_n->rpc_name, ret);
goto err;
}
dev_n->rpc_run = true;
} else {
ddkc_info("rpc service named:%s already started, handle:0x%x\r\n", dev_n->rpc_name, dev_n->rpc_handle);
}
ddkc_dbg("call driver's open operation\n");
if (fops->open) {
ret = (fops->open)(node, fp);
if (ret) {
ddkc_err("open %s failed, ret:%d\n", path_name, ret);
goto err;
}
dev_n->ref_cnt++;
} else {
ddkc_warn("%s:fops->open is NULL\n", path_name);
}
ddkc_dbg("open %s sucess, dev_n->ref_cnt:%d\n", path_name, dev_n->ref_cnt);
res.priv.status = ret;
fnode->dev_n = dev_n;
res.open.farg = fnode;
ddkc_dbg("crpc_handle:0x%x, status:%d, open.farg:%p\r\n", crpc_handle, res.open.status, res.open.farg);
//send open RPC result via aos_rpc_resp
ret = aos_rpc_resp(crpc_handle, 1, sizeof(res), &res);
if (ret) {
ddkc_err("aos_rpc_resp on %s to handle:0x%x failed, ret:0x%x\r\n", path_name, crpc_handle, ret);
if (fops->close)
(fops->close)(fp);
else {
ddkc_warn("%s:fops->close is NULL\n", path_name);
}
dev_n->ref_cnt--;
goto err;
}
// add node info into file_head only when all operations succeed
dlist_add_tail(&fnode->node, &dev_n->file_head);
dlist_add_tail(&fnode->valid, &g_fnode_valid_list);
return 0;
err:
/* check whether rpc service needs to be stopped */
if (dev_n && !dev_n->ref_cnt && dev_n->rpc_run) {
ddkc_info("stop rpc service named:%s, handle:0x%x\r\n", dev_n->rpc_name, dev_n->rpc_handle);
ret = aos_rpc_stop(dev_n->rpc_handle);
if (ret) {
ddkc_err("aos_rpc_stop on %s failed, ret:%d\n", dev_n->rpc_name, ret);
}
dev_n->rpc_run = false;
}
/* clear other resoruce allocated in earlier steps */
if (fnode) {
free(fnode);
fnode = NULL;
}
if (node) {
free(node);
node = NULL;
}
/* send back RPC response to rpc client */
ddkc_err("open %s failed, send rpc resp:%d\r\n", path_name, ret);
res.open.status = ret;
res.open.farg = NULL;
//send open result via aos_rpc_resp
ret = aos_rpc_resp(crpc_handle, 1, sizeof(res), &res);
if (ret)
ddkc_err("aos_rpc_resp to 0x%x failed, ret:0x%x\r\n", crpc_handle, ret);
return ret;
}
/**
* close RPC message handler, called when CLOSE rpc message arrived in main rpc service's handler
*
* @param parg - pointer to u_fops_arg_u
* @param crpc_handle - rpc client's handle,
* response should be send to rpc client no matter this operation succeed or not
*
* @return 0 for success; negative for failure
*/
int u_device_rpc_close(u_fops_arg_u *parg, int crpc_handle) {
int ret = 0;
bool valid = false;
u_fops_result_u res;
file_t *fp = NULL;
file_node_t *fnode = NULL;
char *path_name = NULL;
struct subsys_dev_node *dev_n = NULL;
subsys_file_ops_t *fops = NULL;
if (!parg || !crpc_handle) {
ddkc_err("invalid rpc handle:%d or parg:%p\r\n", crpc_handle, parg);
ret = -EINVAL;
goto err;
}
fnode = (file_node_t *)parg->priv.farg;
/*
* do fnode validation, or permission fault might happen,
* becuase fnode might be other process' memory region
*
*/
valid = _is_valid_fnode(fnode);
if (!valid) {
ddkc_err("fnode:%p is not valid\r\n", fnode);
ret = -EINVAL;
goto err;
}
dev_n = fnode->dev_n;
if (!dev_n->rpc_run) {
ddkc_warn("rpc service is already stopped\r\n");
WARN_ON_MSG(dev_n->ref_cnt, "rpc service is stopped but dev_n->ref_cnt:%d is not 0\r\n", dev_n->ref_cnt);
WARN_ON_MSG(!dlist_empty(&dev_n->file_head), "rpc service is stopped but dev_n->file_head is not empty\r\n");
ret = -EALREADY;
goto err;
}
fp = &fnode->f;
path_name = dev_n->path_name;
ddkc_dbg("closing %s, dev_n->rpc_handle:0x%x\r\n", path_name, dev_n->rpc_handle);
fops = dev_n->fops;
ret = fops->close(fp);
dev_n->ref_cnt--;
if (!ret)
ddkc_dbg("close %s success, ret:%d, dev_n->ref_cnt:%d\r\n", path_name, ret, dev_n->ref_cnt);
else
ddkc_err("close %s failed, ret:%d\r\n", path_name, ret);
if (!dev_n->ref_cnt && dev_n->rpc_run) {
ddkc_err("dev_n->ref_cnt is 0, should stop rpc service named %s\r\n", dev_n->rpc_name);
ret = aos_rpc_stop(dev_n->rpc_handle);
if (ret) {
ddkc_err("aos_rpc_stop on %s failed, ret:%d\n", dev_n->rpc_name, ret);
}
dev_n->rpc_run = false;
}
// delete from device node's file list
dlist_del(&fnode->node);
dlist_del(&fnode->valid);
free(fp->node);
fp->node = NULL;
free(fnode);
ddkc_dbg("close %s %s, send rpc resp:%d\r\n", path_name, ret ? "fail" : "success", ret);
err:
res.close.status = ret;
//send close result via aos_rpc_resp
ret = aos_rpc_resp(crpc_handle, 1, sizeof(res), &res);
if (ret)
ddkc_err("send rpc response to 0x%x failed, ret:0x%x\r\n", crpc_handle, ret);
return ret;
}
#endif
/**
*
* device open stub for delay init required driver
*
* @param node - pointer to inode, device node information
* @param f - pointer to file, file info
*
* @return 0 for success; negative for failure
*/
static int _device_vfs_open (inode_t *node, file_t *f) {
int ret = 0;
dlist_t *pos = NULL;
dlist_t *tmp = NULL;
struct subsys_dev *sdev = NULL;
struct subsys_dev_node *dev_n = (struct subsys_dev_node *)node->i_arg;
ddkc_dbg("dev_n:%p\r\n", dev_n);
if (!dev_n) {
ddkc_err("node->i_arg is NULL, ignore\r\n");
return -EINVAL;
}
ddkc_info("opening %s\r\n", node->i_name);
dlist_for_each_safe(pos, tmp, &g_subsys_dev_list)
{
dev_n = aos_container_of(pos, subsys_dev_node_t, n);
sdev = &dev_n->dev;
if (!strcmp(dev_n->path_name, node->i_name))
break;
dev_n = NULL;
}
if (!dev_n) {
ddkc_err("dev_n not found for %s\r\n", node->i_name);
return -EIO;
}
sdev = &dev_n->dev;
/* check whether real_init or real_probe is always called or not */
if (sdev->delay_init) {
if (dev_n->real_init) {
ret = (dev_n->real_init)(dev_n->pdev);
} else
ret = (dev_n->real_probe)(dev_n->pdev);
if (ret) {
ddkc_err("fail to init/probe for %s, ret:%d\r\n", node->i_name, ret);
return -EIO;
}
sdev->delay_init = false;
node->i_arg = sdev->user_data;
}
/* call real_open provided by driver and logged in aos_dev_reg */
if (dev_n->real_open)
return (dev_n->real_open)(node, f);
return 0;
}
/**
*
* fake driver probe callback for delay init required driver
*
* @param pdev - pointer to the device
*
* @return 0 for success; negative for failure
*/
static int _device_vfs_init(struct u_platform_device *pdev) {
ddkc_dbg("enter\r\n");
return 0;
}
/**
*
* register device driver
*
* @param sdev - pointer to subsys device
* @param sfops - pointer to file operations provided by device driver
* @param sdrv - pointer to device driver speicified operations
* @param rpc_only - whether this driver is rpc driver or not - not used for the moment
*
* @return 0 for success; negative for failure
*/
int aos_dev_reg_with_flag (struct subsys_dev *sdev, subsys_file_ops_t *sfops, struct subsys_drv* sdrv, bool rpc_only) {
int ret = 0;
char *p = NULL;
char *path_name = NULL;
int path_name_len = 0;
struct u_platform_driver *pdrv = NULL;
struct u_platform_device *pdev = NULL;
subsys_file_ops_t *fops = NULL;
struct subsys_dev_node *dev_n = NULL;
char *rpc_name = NULL;
int rpc_handle = 0;
char *main_rpc_name = NULL;
if (!sfops || !sdev || !sdev->node_name) {
ddkc_err("invalid sfops:%p, sdev:%p or name:%p\r\n", sfops, sdev, sdev ? sdev->node_name : NULL);
return -EINVAL;
}
#ifdef USER_SPACE_DRIVER
/* register a rpc service for user space device driver
* with pre-defined service name format - "rpc-<pid>-<node_name>"
*/
rpc_name = (char *)malloc(UDRIVER_RCP_NAME_MAX_LEN);
if (!rpc_name) {
ddkc_err("malloc failed, rpc_name:%p\r\n", rpc_name);
ret = -ENOMEM;
goto err_malloc;
}
ret = snprintf(rpc_name, UDRIVER_RCP_NAME_MAX_LEN, UDRIVER_RPC_NAME_FORMAT, getpid(), sdev->node_name);
if (ret < 0) {
ddkc_err("rpc_name snprintf for node_name:%s failed\r\n", sdev->node_name);
goto err_malloc;
}
ret = aos_rpc_regist(rpc_name, U_CDEV_RPC_BUFFER_SIZE, &rpc_handle);
if (ret) {
ddkc_err("register driver rpc service[%s] failed, ret:%d\r\n", rpc_name, ret);
goto err_malloc;
}
ddkc_dbg("register driver rpc service[%s] for %s succeed, handle:0x%x\r\n",
rpc_name, sdev->node_name, rpc_handle);
#endif
pdev = (struct u_platform_device *)malloc(sizeof(*pdev));
if (pdev) {
memset(pdev, 0, sizeof(*pdev));
} else {
ret = -ENOMEM;
goto err_malloc;
}
pdrv = (struct u_platform_driver *)malloc(sizeof(*pdrv));
if (pdrv) {
memset(pdrv, 0, sizeof(*pdrv));
} else {
ret = -ENOMEM;
goto err_malloc;
}
fops = (subsys_file_ops_t *)malloc(sizeof(*fops));
if (fops) {
memset(fops, 0, sizeof(*fops));
} else {
ret = -ENOMEM;
goto err_malloc;
}
path_name_len = strlen(NODE_PREFIX) + strlen(sdev->node_name) + 1;
path_name = (char *)malloc(path_name_len);
if (path_name) {
memset(path_name, 0, path_name_len);
} else {
ret = -ENOMEM;
goto err_malloc;
}
dev_n = (struct subsys_dev_node *)malloc(sizeof(*dev_n) + strlen(sdev->node_name) + 1);
if (dev_n) {
memset(dev_n, 0, sizeof(*dev_n) + strlen(sdev->node_name) + 1);
} else {
ret = -ENOMEM;
goto err_malloc;
}
//TODO: use sdrv->drv_name later
pdev->name = strdup(sdev->node_name);
if (!pdev->name) {
ddkc_err("dev strdup on %p failed\r\n", sdev->node_name);
ret = -EIO;
goto err_malloc_name;
}
ddkc_dbg("pdev->name:%s\r\n", pdev->name);
pdev->id = 0;
/* register device to u_platform bus */
ret = u_platform_device_register(pdev);
if (ret) {
ddkc_err("u_platform_device_register addplatform_device_register failed, ret:%d\r\n", ret);
ret = -EIO;
goto err_dev_reg;
}
/* log driver's private user_data pointer */
u_platform_set_user_data(pdev, sdev->user_data);
ddkc_dbg("set user_data:%p to user_data of pdev:%p\r\n", sdev->user_data, pdev);
if (sdrv) {
/* for legacy driver */
pdrv->init = (void *)sdrv->init;
pdrv->deinit = (void *)sdrv->deinit;
pdrv->pm = (void *)sdrv->pm;
/* for linux like drivers */
pdrv->probe = (void *)sdrv->probe;
pdrv->remove = (void *)sdrv->remove;
pdrv->suspend = (void *)sdrv->suspend;
pdrv->resume = (void *)sdrv->resume;
pdrv->shutdown = (void *)sdrv->shutdown;
} else
ddkc_dbg("sdrv callback is not set\r\n");
pdrv->driver.name = strdup(sdev->node_name);
if (!pdrv->driver.name) {
ddkc_dbg("drv strdup on %p failed\r\n", sdev->node_name);
ret = -ENOMEM;
goto err_dev_reg;
}
if (sdev->delay_init) {
dev_n->real_init = pdrv->init;
pdrv->init = _device_vfs_init;
dev_n->real_probe = pdrv->probe;
pdrv->probe = _device_vfs_init;
}
ddkc_dbg("pdrv->name:%s\r\n", pdrv->driver.name);
/* register driver to u_platform bus
* driver init/probe callback will be called in this step
* */
ret = u_platform_driver_register(pdrv);
if (ret) {
ddkc_err("u_platform_driver_register failed, ret:%d\r\n", ret);
ret = -EIO;
goto err_drv_reg;
}
memcpy(fops, sfops, sizeof(*fops));
p = path_name;
strncpy(path_name, NODE_PREFIX, strlen(NODE_PREFIX) + 1);
p += strlen(NODE_PREFIX);
strncpy(p, sdev->node_name, strlen(sdev->node_name) + 1);
dlist_init(&dev_n->n);
memcpy(&dev_n->dev, sdev, sizeof(*sdev));
dev_n->dev.node_name = (char *)(dev_n + 1);
strncpy(dev_n->dev.node_name, sdev->node_name, strlen(sdev->node_name));
// log device rpc handle and rpc_name
#ifdef USER_SPACE_DRIVER
dev_n->rpc_handle = rpc_handle;
dev_n->rpc_name = rpc_name;
main_rpc_name = u_driver_get_main_service_name();
#else
dev_n->rpc_name = NULL;
main_rpc_name = NULL;
#endif
dev_n->path_name = path_name;
dev_n->fops = fops;
dev_n->pdev = pdev;
dev_n->pdrv = pdrv;
dev_n->ref_cnt = 0;
dev_n->rpc_run = false;
dlist_init(&dev_n->file_head);
dlist_add_tail(&dev_n->n, &g_subsys_dev_list);
ddkc_dbg("registering %s to vfs\r\n", path_name);
ddkc_dbg("main rpc name:%s, rpc_name:%s\r\n", main_rpc_name, dev_n->rpc_name);
if (sdev->delay_init) {
dev_n->real_open = fops->open;
fops->open = _device_vfs_open;
}
#ifdef USER_SPACE_DRIVER
ret = aos_union_register_driver(path_name, fops, sdev->delay_init ? dev_n : sdev->user_data, main_rpc_name, dev_n->rpc_name);
#else
ret = aos_register_driver(path_name, fops, sdev->delay_init ? dev_n : sdev->user_data);
#endif
if (ret) {
dlist_del(&dev_n->n);
ddkc_info("register %s to vfs failed, rpc_only:%d, sdev->delay_init:%d, ret:%d\r\n", path_name, rpc_only, sdev->delay_init, ret);
goto err_vfs_reg;
}
ddkc_dbg("register %s to vfs success, rpc_only:%d, sdev->delay_init:%d\r\n", path_name, rpc_only, sdev->delay_init);
return 0;
err_vfs_reg:
// unregiste rpc service and free rpc service name field
u_platform_driver_unregister(pdrv);
err_drv_reg:
u_platform_device_unregister(pdev);
err_dev_reg:
err_malloc_name:
if (pdev->name)
free((void *)pdev->name);
pdev->name = NULL;
err_malloc:
if (pdev) {
free(pdev);
pdev = NULL;
}
if (pdrv) {
if (pdrv->driver.name)
free(pdrv->driver.name);
free(pdrv);
pdrv = NULL;
}
if (path_name) {
free(path_name);
path_name = NULL;
}
if (fops) {
free(fops);
fops = NULL;
}
if (dev_n) {
free(dev_n);
dev_n = NULL;
}
#ifdef USER_SPACE_DRIVER
if (rpc_handle) {
aos_rpc_close(rpc_handle);
rpc_handle = 0;
}
if (rpc_name) {
free(rpc_name);
rpc_name = NULL;
}
#endif
ddkc_err("device register failed, ret:%d\r\n", ret);
return ret;
}
/**
*
* register device array
*
* @param sdev pointer to devices array be register
* @param size device array size
* @param sfops file operations API
* @param sdrv - device driver operations callback
* - probe will be called when device exist
* - remove will be called when aos_dev_unreg is called
* @return 0 for success; negative for failure
*/
int aos_devs_reg(struct subsys_dev *sdev[], int size, subsys_file_ops_t *sfops, struct subsys_drv* sdrv) {
int i = 0;
int ret = 0;
for (i = 0; i < size; i++) {
ret = aos_dev_reg(sdev[i], sfops, sdrv);
if (ret) {
i--;
goto err;
}
}
return 0;
err:
for (; i >= 0; i--) {
int ret = 0;
ret = aos_dev_unreg(sdev[i]);
if (ret) {
ddkc_err("unregister device %s failed\r\n", sdev[i]->node_name);
}
}
return ret;
}
/**
* unregister device driver
*
* @param sdev - device identifier, name and type must be carefully set
*
* @return 0 if device register success; return negative error no. if device register fails
*/
int aos_dev_unreg(struct subsys_dev *sdev) {
int ret = 0;
char *p = NULL;
char *path_name = NULL;
int path_name_len = 0;
subsys_dev_node_t *dev_n = NULL;
dlist_t *pos = NULL;
dlist_t *tmp = NULL;
struct subsys_dev *d = NULL;
path_name_len = strlen(NODE_PREFIX) + strlen(sdev->node_name) + 1;
path_name = (char *)malloc(path_name_len);
memset(path_name, 0, path_name_len);
p = path_name;
strncpy(p, NODE_PREFIX, strlen(NODE_PREFIX));
p += strlen(NODE_PREFIX);
strncpy(p, sdev->node_name, strlen(sdev->node_name));
ddkc_info("unregistering %s from vfs\r\n", path_name);
#ifdef USER_SPACE_DRIVER
ret = aos_union_unregister_driver(path_name);
#else
ret = aos_unregister_driver(path_name);
#endif
ddkc_info("unregister %s from vfs %s\r\n", path_name, !ret ? "success" : "failed");
free(path_name);
ret = -1;
/* enumberate device list for target subsys device node to be removed */
dlist_for_each_safe(pos, tmp, &g_subsys_dev_list) {
dev_n = aos_container_of(pos, subsys_dev_node_t, n);
d = &dev_n->dev;
if(d->type == sdev->type && !strcmp(d->node_name, sdev->node_name) && d->user_data == sdev->user_data) {
ddkc_info("sdev named with %s found, delete it\r\n", d->node_name);
// unregiste rpc service and free rpc service name field
#ifdef USER_SPACE_DRIVER
/* close rpc servce for user space driver */
aos_rpc_close(dev_n->rpc_handle);
free(dev_n->rpc_name);
#endif
u_platform_driver_unregister(dev_n->pdrv);
u_platform_device_unregister(dev_n->pdev);
dlist_del(&dev_n->n);
/* free all resources */
free((void *)dev_n->pdev->name);
free(dev_n->pdev);
free(dev_n->pdrv->driver.name);
free(dev_n->pdrv);
free(dev_n->path_name);
free(dev_n->fops);
free(dev_n);
ret = 0;
break;
}
}
ddkc_err("device unregister %s, ret:%d\r\n", ret ? "fail" : "success", ret);
return ret;
}
/**
*
* register devices and corresponding driver into device/driver module
*
* @param sdev - device identifier, name and type must be carefully set
* @param sfops - file operations API
* @param sdrv - device driver operations callback
* - init/probe will be called when device exist
* - deinit/remove will be called when aos_dev_unreg is called
* @return 0 if device register success; return negative error no. if device register fails
*/
int aos_dev_reg(struct subsys_dev *sdev, subsys_file_ops_t *sfops, struct subsys_drv* sdrv) {
return aos_dev_reg_with_flag(sdev, sfops, sdrv, false);
}
/**
* This function is not used for the moment
* register remote devices/driver into device/driver module, only support rpc mode
*
* @param sdev - device identifier, name and type must be carefully set
* @param sfops - file operations API
* @param sdrv - device driver operations callback
* - probe will be called when device exist
* - remove will be called when aos_dev_unreg is called
* @return 0 if device register success; return negative error no. if device register fails
*/
int aos_remote_dev_reg(struct subsys_dev *sdev, subsys_file_ops_t *sfops, struct subsys_drv* sdrv) {
return aos_dev_reg_with_flag(sdev, sfops, sdrv, true);
}
/**
* unregister device array
*
* @param sdev - pointer to devices array be register
* @param size - device array size
*
* @return 0 if device register success; return negative error no. if device register fails
*/
int aos_devs_unreg(struct subsys_dev *sdev[], int size) {
int i = 0;
int ret = 0;
for (i = 0; i < size; i++) {
ret = aos_dev_unreg(sdev[i]);
}
return ret;
}
/**
*
* device vfs core layer initialization
* declared with EARLY_DRIVER_ENTRY, which is before vendor driver initialization
*
* @return always return 0
*
*/
int device_vfs_init(void) {
#ifdef AOS_COMP_VFS
aos_vfs_init();
#endif
dlist_init(&g_subsys_dev_list);
dlist_init(&g_fnode_valid_list);
return 0;
}
EARLY_DRIVER_ENTRY(device_vfs_init)
| YifuLiu/AliOS-Things | components/drivers/core/base/devicevfs/src/device_vfs_core.c | C | apache-2.0 | 34,139 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <stddef.h>
#ifdef USER_SPACE_DRIVER
#include <rpc.h>
#endif
#include <drivers/char/u_device.h>
#include <drivers/u_ld.h>
#include <drivers/char/u_device.h>
#include <drivers/char/u_cdev_msg.h>
extern long __core_driver_start__;
extern long __core_driver_end__;
extern long __bus_driver_start__;
extern long __bus_driver_end__;
extern long __vfs_driver_start__;
extern long __vfs_driver_end__;
extern long __early_driver_start__;
extern long __early_driver_end__;
extern long __level0_driver_start__;
extern long __level0_driver_end__;
extern long __level1_driver_start__;
extern long __level1_driver_end__;
extern long __level2_driver_start__;
extern long __level2_driver_end__;
extern long __level3_driver_start__;
extern long __level3_driver_end__;
extern long __post_driver_start__;
extern long __post_driver_end__;
struct section_info {
OS_DRIVER_ENTRY *s;
OS_DRIVER_ENTRY *e;
};
#define DODE(x) (OS_DRIVER_ENTRY *)(x)
/**
* all driver entry declared with XXXX_DRIVER_ENTRY or XXXX_DRIVER_FULL_ENTRY (POST is excluded) will be called with specified
* sequence
*
* @return 0 for success; negative error no. for failure
*/
int _os_driver_entry(void) {
int i = 0;
OS_DRIVER_ENTRY *s = NULL;
OS_DRIVER_ENTRY *e = NULL;
OS_DRIVER_ENTRY *drv_entry = NULL;
struct section_info g_drv_section_entry[] = {
{DODE(&__core_driver_start__), DODE(&__core_driver_end__)},
{DODE(&__bus_driver_start__), DODE(&__bus_driver_end__)},
{DODE(&__early_driver_start__), DODE(&__early_driver_end__)},
{DODE(&__vfs_driver_start__), DODE(&__vfs_driver_end__)},
{DODE(&__level0_driver_start__), DODE(&__level0_driver_end__)},
{DODE(&__level1_driver_start__), DODE(&__level1_driver_end__)},
{DODE(&__level2_driver_start__), DODE(&__level2_driver_end__)},
{DODE(&__level3_driver_start__), DODE(&__level3_driver_end__)},
};
for (i = 0; i < sizeof(g_drv_section_entry)/sizeof(g_drv_section_entry[0]); i++) {
s = g_drv_section_entry[i].s;
e = g_drv_section_entry[i].e;
drv_entry = s;
while (drv_entry < e) {
ddkc_dbg("drv_entry:%p, *drv_entry:%p\r\n", drv_entry, *drv_entry);
(*((OS_DRIVER_ENTRY *)drv_entry))();
drv_entry++;
}
}
return 0;
}
/**
* all driver entry declared with POST_DRIVER_ENTRY or POST_DRIVER_FULL_ENTRY will be called with specified
* sequence
*
* @return 0 for success; negative error no. for failure
*/
int _os_post_driver_entry(void) {
int i = 0;
OS_DRIVER_ENTRY *s = NULL;
OS_DRIVER_ENTRY *e = NULL;
OS_DRIVER_ENTRY *drv_entry = NULL;
struct section_info g_drv_section_entry[] = {
{DODE(&__post_driver_start__), DODE(&__post_driver_end__)},
};
for (i = 0; i < sizeof(g_drv_section_entry)/sizeof(g_drv_section_entry[0]); i++) {
s = g_drv_section_entry[i].s;
e = g_drv_section_entry[i].e;
drv_entry = s;
while (drv_entry < e) {
ddkc_dbg("drv_entry:%p, *drv_entry:%p\r\n", drv_entry, *drv_entry);
(*((OS_DRIVER_ENTRY *)drv_entry))();
drv_entry++;
}
}
return 0;
}
| YifuLiu/AliOS-Things | components/drivers/core/base/devicevfs/src/u_driver_hub.c | C | apache-2.0 | 3,256 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <drivers/bug.h>
#include <drivers/u_ld.h>
#include <drivers/char/u_device.h>
#include <drivers/char/u_cdev_msg.h>
#include <devicevfs/devicevfs_rpc.h>
#ifdef USER_SPACE_DRIVER
#include <rpc.h>
#define UDRIVER_RPC_BUFFER_SIZE (1024)
#define UDRIVER_RPC_NAME_FORMAT "rpc-%d-main"
static char g_main_rpc_name[16] = {0};
static int g_udriver_rpc_handle = 0;
static char g_main_rpc_buf[UDRIVER_RPC_BUFFER_SIZE] = {0};
static int _cdev_fops_handler(int crpc_handle, u_cdev_msg_t *p_msg);
static int _loop_msg_handler(int crpc_handle, u_cdev_msg_t *p_msg);
static u_cdev_msg_handler _cdev_msg_handler[CDEV_MSG_MAX] = {
[CDEV_MSG_FOPS] = _cdev_fops_handler,
[CDEV_MSG_LOOP] = _loop_msg_handler,
};
int _loop_msg_handler(int crpc_handle, u_cdev_msg_t *p_msg) {
ddkc_info("%s\r\n", __func__);
return 0;
}
int _cdev_fops_handler(int reply_handle, u_cdev_msg_t *p_msg) {
int ret = 0;
u_cdev_msg_ie_t *ie = NULL;
u_fops_arg_u *parg = NULL;
if (!p_msg) {
return -EINVAL;
}
ie = p_msg->v;
ddkc_dbg("sizeof(u_cdev_msg_t):%d, sizeof(u_cdev_msg_id_e):%d, sizeof(unsigned short):%d, sizeof(ie->t):%d, ie->t:%d\r\n",
sizeof(u_cdev_msg_t), sizeof(u_cdev_msg_id_e), sizeof(unsigned short),
sizeof(ie->t), ie->t);
switch(ie->t) {
case FOPS_OPEN:
parg = (u_fops_arg_u *)ie->v;
ret = u_device_rpc_open(parg, reply_handle);
ddkc_dbg("open %s return %d\r\n", parg->open.path, ret);
break;
case FOPS_CLOSE:
parg = (u_fops_arg_u *)ie->v;
ret = u_device_rpc_close(parg, reply_handle);
ddkc_dbg("close return %d\r\n", ret);
break;
default:
ddkc_err("invalid file operation:%d, ignore\r\n", ie->t);
ret = -EINVAL;
break;
}
return ret;
}
void main_thread_req_arrived(struct aos_parcel_t *pkt) {
int ret = 0;
int reply_handle = 0;
u_cdev_msg_t *p_msg = NULL;
size_t len = sizeof(int);
if (!pkt || !pkt->max_size) {
ddkc_err("invalid pkt:%p or max_size:%d\r\n", pkt, pkt ? pkt->max_size : 0);
return;
}
ddkc_dbg("pkt->max_size:%x\r\n", pkt->max_size);
aos_parcel_get(AP_UVARINT, &reply_handle, &len, pkt);
ddkc_dbg("reply_handle:%x\r\n", reply_handle);
BUG_ON_MSG((pkt->max_size > sizeof(g_main_rpc_buf)),
"rpc max_size:%d > main thread rpc buf len:%d",
pkt->max_size, sizeof(g_main_rpc_buf));
len = pkt->max_size;
ddkc_dbg("max_size:%x\r\n", len);
ret = aos_parcel_get(AP_BUF, g_main_rpc_buf, &len, pkt);
if (ret < 0 || len <= 0) {
ddkc_err("rpc receive data failed, ret:%d\r\n", ret);
// TODO: how to handle this case?
return;
}
p_msg = (u_cdev_msg_t *)g_main_rpc_buf;
BUG_ON_MSG((p_msg->t >= CDEV_MSG_MAX),
"p_msg->t:%d > CDEV_MSG_MAX:%d\r\n", p_msg->t, CDEV_MSG_MAX);
#if 0
for (int i = 0;i < len; i++)
ddkc_err("i:%d - 0x%x\n", i, g_main_rpc_buf[i]);
#endif
ret = (_cdev_msg_handler[p_msg->t](reply_handle, p_msg));
if (ret) {
ddkc_err("rpc msg handle failed, ret:%d\r\n", ret);
}
return;
}
void main_thread_event_cb(int eid, void * event) {
struct aos_revt_param_t *param = (struct aos_revt_param_t *)event;
int reason = *(int *)param->param;
if (eid != RPC_EID_STOP) {
ddkc_warn("eid:%d, reason:%d, closing rpc service - handle:0x%x\r\n", eid, reason, param->srpc_handle);
aos_rpc_close(param->srpc_handle);
} else
ddkc_info("eid:%d, reason:%d\r\n", eid, reason);
return;
}
#endif
/**
* this is the only driver entry API, when a driver is selected, must call this API in proper place
*
* @string process identification
*
* @return 0 for success; negative error number for failure
*/
int u_driver_entry(char* string) {
int ret = -1;
#ifdef USER_SPACE_DRIVER
ddkc_dbg("%s uspace mode:%d\r\n", __func__, 1);
/* register main thread service into PM */
ret = snprintf(g_main_rpc_name, sizeof(g_main_rpc_name), UDRIVER_RPC_NAME_FORMAT, getpid());
if (ret <= 0) {
ddkc_err("snprintf for main rpc name failed\r\n");
return ret;
}
ret = aos_rpc_regist(g_main_rpc_name, UDRIVER_RPC_BUFFER_SIZE, &g_udriver_rpc_handle);
if (ret) {
ddkc_err("register main rpc service[%s] failed, ret:%d\r\n", g_main_rpc_name, ret);
return ret;
}
ddkc_dbg("register main rpc main service[%s] succeed, handle:0x%x\r\n",
g_main_rpc_name, g_udriver_rpc_handle);
ret = aos_rpc_run(g_udriver_rpc_handle, main_thread_req_arrived, main_thread_event_cb);
if (ret) {
ddkc_err("aos_rpc_run on service:%s fails, ret:%d\r\n", g_main_rpc_name, ret);
goto error;
}
#else
ddkc_info("%s uspace mode:%d\r\n", __func__, 0);
#endif
#if (AOS_COMP_IRQ > 0)
extern int aos_irq_system_init(void);
ret = aos_irq_system_init();
if (ret) {
ddkc_err("irq system init failed, ret:%d\r\n", ret);
goto error;
}
#endif
ret = _os_driver_entry();
if (ret) {
ddkc_err("_os_driver_entry error, ret:%d\r\n", ret);
goto error;
}
return 0;
error:
#ifdef USER_SPACE_DRIVER
if (g_udriver_rpc_handle) {
aos_rpc_close(g_udriver_rpc_handle);
g_udriver_rpc_handle = 0;
}
#if 0
u_irq_system_deinit();
#endif
#endif
return ret;
}
/**
* this is the only driver entry API, when a driver is selected, must call this API in proper place
*
* @string process identification
*
* @return 0 for success; negative error number for failure
*/
int u_post_driver_entry(char* string) {
int ret = -1;
ret = _os_post_driver_entry();
return ret;
}
/**
*
* @return main thread's RPC service name
*/
char *u_driver_get_main_service_name(void) {
#ifdef USER_SPACE_DRIVER
return g_main_rpc_name;
#else
return NULL;
#endif
}
| YifuLiu/AliOS-Things | components/drivers/core/base/devicevfs/src/u_driver_main.c | C | apache-2.0 | 6,098 |
/*
* Copyright (C) 2020-2021 Alibaba Group Holding Limited
*/
#ifndef AOS_DEVICE_H
#define AOS_DEVICE_H
#include <aos/kernel.h>
typedef enum {
AOS_DEV_TYPE_MISC = 0,
AOS_DEV_TYPE_INTC,
AOS_DEV_TYPE_TTY,
AOS_DEV_TYPE_GPIOC,
AOS_DEV_TYPE_GPIO,
AOS_DEV_TYPE_WATCHDOG,
AOS_DEV_TYPE_ETHERNET,
AOS_DEV_TYPE_WLAN,
AOS_DEV_TYPE_DISK,
AOS_DEV_TYPE_DISKPART,
AOS_DEV_TYPE_FLASH,
AOS_DEV_TYPE_FLASHPART,
AOS_DEV_TYPE_RTC,
AOS_DEV_TYPE_SPI,
AOS_DEV_TYPE_I2C,
AOS_DEV_TYPE_ADC,
AOS_DEV_TYPE_DAC,
AOS_DEV_TYPE_PWM,
AOS_DEV_TYPE_HWTIMER,
} aos_dev_type_t;
struct aos_dev;
typedef struct aos_dev_ref {
struct aos_dev *dev;
void *pdata;
} aos_dev_ref_t;
#define AOS_DEV_REF_INIT_VAL { .dev = NULL, .pdata = NULL, }
#define aos_dev_ref_init(ref) do { *(ref) = (aos_dev_ref_t)AOS_DEV_REF_INIT_VAL; } while (0)
#define aos_dev_ref_is_valid(ref) (!!(ref)->dev)
#ifdef __cplusplus
extern "C" {
#endif
aos_status_t aos_dev_get(aos_dev_ref_t *ref, aos_dev_type_t type, uint32_t id);
void aos_dev_put(aos_dev_ref_t *ref);
#ifdef __cplusplus
}
#endif
#endif /* AOS_DEVICE_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/device.h | C | apache-2.0 | 1,184 |
/*
* Copyright (C) 2020-2021 Alibaba Group Holding Limited
*/
#ifndef AOS_DEVICE_CORE_H
#define AOS_DEVICE_CORE_H
#include <aos/kernel.h>
#include <aos/list.h>
#include <k_rbtree.h>
#include <aos/device.h>
#ifdef AOS_COMP_DEVFS
#include <aos/devfs.h>
#endif
#if defined(CONFIG_DRV_CORE) && CONFIG_DRV_CORE != 0
#include <drivers/u_ld.h>
#endif
struct aos_dev_ops;
typedef struct aos_dev {
aos_dev_type_t type;
uint32_t id;
const struct aos_dev_ops *ops;
#ifdef AOS_COMP_DEVFS
aos_devfs_node_t devfs_node;
#endif
struct k_rbtree_node_t rb_node;
aos_sem_t rb_sem;
aos_mutex_t mutex;
uint32_t ref_count;
} aos_dev_t;
typedef struct aos_dev_ops {
void (*unregister)(aos_dev_t *);
aos_status_t (*get)(aos_dev_ref_t *);
void (*put)(aos_dev_ref_t *);
} aos_dev_ops_t;
#define aos_dev_lock(dev) do { (void)aos_mutex_lock(&(dev)->mutex, AOS_WAIT_FOREVER); } while (0)
#define aos_dev_unlock(dev) do { (void)aos_mutex_unlock(&(dev)->mutex); } while (0)
#define aos_dev_ref_is_first(ref) ((ref)->dev->ref_count == 0)
#define aos_dev_ref_is_last(ref) ((ref)->dev->ref_count == 0)
#ifdef __cplusplus
extern "C" {
#endif
#if !(defined(CONFIG_DRV_CORE) && CONFIG_DRV_CORE != 0)
aos_status_t aos_dev_core_init(void);
#endif
aos_status_t aos_dev_register(aos_dev_t *dev);
aos_status_t aos_dev_unregister(aos_dev_type_t type, uint32_t id);
aos_status_t aos_dev_ref(aos_dev_ref_t *ref, aos_dev_t *dev);
#ifdef __cplusplus
}
#endif
#endif /* AOS_DEVICE_CORE_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/device_core.h | C | apache-2.0 | 1,538 |
/**
* @file can.h
* @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef HAL_CAN_H
#define HAL_CAN_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
/** @addtogroup hal_can CAN
* CAN hal API.
*
* @{
*/
/*
* CAN handle configuration
*/
typedef struct {
uint32_t baud_rate; /**< baud rate of can */
uint8_t ide; /**< 0:normal can, 1:extend can */
uint8_t auto_bus_off; /**< 1:enable auto bus off, 0:disable */
uint8_t auto_retry_transmit; /**< 1:enable retry transmit, 0:disable */
} can_config_t;
/*
* CAN device description
*/
typedef struct {
uint8_t port; /**< can port */
can_config_t config; /**< can config */
void *priv; /**< priv data */
} can_dev_t;
/*
* CAN frameheader config
*/
typedef struct {
uint32_t id; /**< id of can */
uint8_t rtr; /**< 0:data frame, 1:remote frame */
uint8_t dlc; /**< must <=8 */
} can_frameheader_t;
/*
* CAN filter_item config
*/
typedef struct{
uint8_t rtr; /**< 0:data frame, 1:remote frame */
uint32_t check_id; /**< the filter identification number */
uint32_t filter_mask; /**< the filter mask number or identification number */
} can_filter_item_t;
/**
* Initialises a CAN interface
*
* @param[in] can the interface which should be initialised
*
* @return 0 : on success, EINVAL : if an error occurred with any step
*/
int32_t hal_can_init(can_dev_t *can);
/**
* config a CAN fliter
*
* @param[in] can the interface which should be initialised
* @param[in] filter_grp_cnt 0 will make all id pass. This value must be <=10
* @param[in] filter_config point to a filter config
*
* @return 0 : on success, EIO : if an error occurred with any step
*/
int32_t hal_can_filter_init(can_dev_t *can, const uint8_t filter_grp_cnt, can_filter_item_t *filter_config);
/**
* Transmit data by CAN
*
* @param[in] can the can interface
* @param[in] tx_header frame head
* @param[in] data pointer to the start of data
* @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER
* if you want to wait forever
*
* @return 0 : on success, EIO : if an error occurred with any step
*/
int32_t hal_can_send(can_dev_t *can, can_frameheader_t *tx_header, const void *data, const uint32_t timeout);
/**
* Receive data by CAN
*
* @param[in] can the can interface
* @param[out] rx_header frame head
* @param[out] data pointer to the start of data
* @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER
* if you want to wait forever
*
* @return 0 : on success, EIO : if an error occurred with any step
*/
int32_t hal_can_recv(can_dev_t *can, can_frameheader_t *rx_header, void *data, const uint32_t timeout);
/**
* Deinitialises a CAN interface
*
* @param[in] can the interface which should be deinitialised
*
* @return 0 : on success, EIO : if an error occurred with any step
*/
int32_t hal_can_finalize(can_dev_t *can);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* HAL_CAN_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/hal/can.h | C | apache-2.0 | 3,185 |
/**
* @file i2s.h
* @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef HAL_I2S_H
#define HAL_I2S_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup hal_i2s I2S
* i2s hal API.
*
* @{
*/
#include <stdint.h>
/* Define the wait forever timeout macro */
#define HAL_WAIT_FOREVER 0xFFFFFFFFU
/*
* I2S mode
*/
typedef enum {
MODE_SLAVE_TX,
MODE_SLAVE_RX,
MODE_MASTER_TX,
MODE_MASTER_RX
} hal_i2s_mode_t;
/*
* I2S standard
*/
typedef enum {
STANDARD_PHILIPS, /**< Philips standard */
STANDARD_MSB, /**< MSB align standard */
STANDARD_LSB, /**< LSB align standard */
STANDARD_PCM_SHORT, /**< PCM short frame standard */
STANDARD_PCM_LONG /**< PCM long frame standard */
} hal_i2s_std_t;
/*
* I2S data format
*/
typedef enum {
DATAFORMAT_16B, /**< 16 bit dataformat */
DATAFORMAT_16B_EXTENDED, /**< 16 bit externded dataformat, 32 bit frame */
DATAFORMAT_24B, /**< 24 bit dataformat */
DATAFORMAT_32B /**< 32 bit dataformat */
} hal_i2s_data_format_t;
/*
* I2S configuration
*/
typedef struct {
uint32_t freq; /**< I2S communication frequency */
hal_i2s_mode_t mode; /**< I2S operating mode */
hal_i2s_std_t standard; /**< I2S communication standard */
hal_i2s_data_format_t data_format; /**< I2S communication data format */
} i2s_config_t;
/*
* I2S device description
*/
typedef struct {
uint8_t port; /* I2S port */
i2s_config_t config; /* I2S config */
void *priv; /* Priv data */
} i2s_dev_t;
/**
* Initialises a I2S dev
*
* @param[in] i2s the dev which should be initialised
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_i2s_init(i2s_dev_t *i2s);
/**
* Transmit data on a I2S dev
*
* @param[in] i2s the I2S dev
* @param[in] data pointer to the start of data
* @param[in] size number of bytes to transmit
* @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER
* if you want to wait forever
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_i2s_send(i2s_dev_t *i2s, const void *data, uint32_t size, uint32_t timeout);
/**
* Receive data on a I2S dev
*
* @param[in] i2s the I2S dev
* @param[out] data pointer to the buffer which will store incoming data
* @param[in] size number of bytes to receive
* @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER
* if you want to wait forever
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_i2s_recv(i2s_dev_t *i2s, void *data, uint32_t size, uint32_t timeout);
/**
* Pause a I2S dev
*
* @param[in] i2s the dev which should be paused
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_i2s_pause(i2s_dev_t *i2s);
/**
* Resume a I2S dev
*
* @param[in] i2s the dev which should be resumed
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_i2s_resume(i2s_dev_t *i2s);
/**
* Stop a I2S dev
*
* @param[in] i2s the dev which should be stopped
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_i2s_stop(i2s_dev_t *i2s);
/**
* finalize a I2S dev
*
* @param[in] i2s the dev which should be finalized
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_i2s_finalize(i2s_dev_t *i2s);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* HAL_I2S_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/hal/i2s.h | C | apache-2.0 | 3,533 |
/**
* @file interpt.h
* @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef HAL_INTERPT_H
#define HAL_INTERPT_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup hal_interpt INTERPT
* interpt hal API.
*
* @{
*/
#include <stdint.h>
/* interrupt proc handle */
typedef void (*hal_interpt_t)(int32_t vec, void *para);
/**
* Interrupt vector init
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_interpt_init(void);
/**
* Mask specified interrupt vector
*
*
* @param[in] vec specified interrupt vector
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_interpt_mask(int32_t vec);
/**
* Unmask specified interrupt vector
*
*
* @param[in] vec specified interrupt vector
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_interpt_umask(int32_t vec);
/**
* Install specified interrupt vector
*
*
* @param[in] vec specified interrupt vector
* @param[in] handler interrupt handler
* @param[in] para interrupt handler args
* @param[in] vec specified interrupt vector
* @param[in] name interrupt descript name
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_interpt_install(int32_t vec, hal_interpt_t handler, void *para, char *name);
#ifdef __cplusplus
}
#endif
#endif /* HAL_INTERPT_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/hal/interpt.h | C | apache-2.0 | 1,343 |
/**
* @file nand.h
* @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef HAL_NAND_H
#define HAL_NAND_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup hal_nand NAND
* nand hal API.
*
* @{
*/
#include <stdint.h>
typedef struct {
uint32_t page_size; /**< NAND memory page size w/o spare area */
uint32_t spare_area_size; /**< NAND memory spare area size */
uint32_t block_size; /**< NAND memory block size number of pages */
uint32_t zone_size; /**< NAND memory zone size measured in number of blocks */
uint32_t zone_number; /**< NAND memory number of zones */
} nand_config_t;
typedef struct {
uint16_t page; /**< NAND memory Page address */
uint16_t block; /**< NAND memory Block address */
uint16_t zone; /**< NAND memory Zone address */
} nand_addr_t;
typedef struct {
uint32_t base_addr; /**< NAND memory base address */
nand_config_t config; /**< NAND device config args */
void *priv; /**< NAND device priv args */
} nand_dev_t;
/**
* Initialises a nand flash interface
*
* @param[in] nand the interface which should be initialised
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nand_init(nand_dev_t *nand);
/**
* Deinitialises a nand flash interface
*
* @param[in] nand the interface which should be Deinitialised
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nand_finalize(nand_dev_t *nand);
/**
* Read nand page(s)
*
* @param[in] nand the interface which should be Readed
* @param[out] data pointer to the buffer which will store incoming data
* @param[in] addr nand address
* @param[in] page_count the number of pages to read
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nand_read_page(nand_dev_t *nand, nand_addr_t *addr, uint8_t *data, uint32_t page_count);
/**
* Write nand page(s)
*
* @param[in] nand the interface which should be Writed
* @param[in] data pointer to source buffer to write
* @param[in] addr nand address
* @param[in] page_count the number of pages to write
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nand_write_page(nand_dev_t *nand, nand_addr_t *addr, uint8_t *data, uint32_t page_count);
/**
* Read nand spare area
*
* @param[in] nand the interface which should be Readed
* @param[out] data pointer to the buffer which will store incoming data
* @param[in] addr nand address
* @param[in] data_len the number of spares to read
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nand_read_spare(nand_dev_t *nand, nand_addr_t *addr, uint8_t *data, uint32_t data_len);
/**
* Write nand spare area
*
* @param[in] nand the interface which should be Writed
* @param[in] data pointer to source buffer to write
* @param[in] addr nand address
* @param[in] data_len the number of spares to write
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nand_write_spare(nand_dev_t *nand, nand_addr_t *addr, uint8_t *data, uint32_t data_len);
/**
* Erase nand block
*
* @param[in] nand the interface which should be Erased
* @param[in] addr nand address
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nand_erase_block(nand_dev_t *nand, nand_addr_t *addr);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* HAL_NAND_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/hal/nand.h | C | apache-2.0 | 3,487 |
#ifndef _NAND_FLASH_HAL_
#define _NAND_FLASH_HAL_
#include <hal/flash.h>
typedef struct {
/* manufacturer ID */
uint8_t mid;
/* Device ID */
uint8_t did;
/* Organization ID */
uint8_t oid;
/* internal chip number:
* 0b00 - 1,
* 0b01 - 2,
* 0b10 - 4,
* 0b11 - 8
*/
uint8_t internal_chip_number:2;
/* cell type:
* 0b00 : 2-level cell,
* 0b01 : 4-level cell,
* 0b10 : 8-level cell,
* 0b11 : 16-level cell,
*/
uint8_t cell_type:2;
/* Number of simutaneously programmed pages:
* 0b00 - 1
* 0b01 - 2
* 0b10 - 4
* 0b11 - 8
*/
uint8_t spages:2;
/* Interleave program between multiple chips:
* 0b0 - not supported
* 0b1 - supported
*/
uint8_t interleave_prog:1;
/* Cache program:
* 0b0 - not supported
* 0b1 - supported
*/
uint8_t cache_prog:1;
/* Page size (witout spare area):
* 0b00 - 1kB
* 0b01 - 2kB
* 0b10 - 4kB
* 0b11 - 8kB
*/
uint8_t page_size:2;
/* Block Size (without spare area):
* 0b00 - 64kB
* 0b01 - 128kB
* 0b10 - 256kB
* 0b11 - 512kB
*/
uint8_t block_size:2;
/* Spare ares size:
* 0b0000 - 8 Bytes
* 0b0001 - 16 Bytes
* 0b0010 - 32 Bytes
* 0b0011 - 64 Bytes
* 0b0100 - 128 Bytes
* 0b0101 - 256 Bytes
* 0b0110 - 512 Bytes
* 0b0111 - 1024 Bytes
* other - reserved
*/
uint8_t spare_size:4;
/* Plane number
* 0b00 - 1
* 0b01 - 2
* 0b10 - 4
* 0b11 - 8
*/
uint8_t plane_number:2;
/* Plane size (without spare area):
* 0b000 - 64Mb
* 0b001 - 128Mb
* 0b010 - 256Mb
* 0b011 - 512Mb
* 0b000 - 1Gb
* 0b000 - 2Gb
* 0b000 - 4Gb
* 0b000 - reserved
*/
uint8_t plane_size:3;
uint8_t reserved:3;
} nand_flash_id_t;
/**
* Read ID of NAND Flash.
*
* @param[out] id The NAND Flash ID information structure.
*
* @return HAL_FLASH_ERR_OK : Success, otherwise failure
*/
hal_flash_err_t hal_flash_read_id(nand_flash_id_t *id);
/**
* Check offset in partition at partition id is a bad block or not for nand
*
* @param[in] in_partition The target flash logical partition which should be check
* @param[in] off_set Point to the address in partition
*
* @return 0 : Good block, 1: Bad block, EIO : If an error occurred with any step
*/
int hal_flash_isbad (hal_partition_t in_partition, uint32_t off_set);
/**
* Markbad at offset in partition at partition id for nand
*
* @param[in] in_partition The target flash logical partition which should be check
* @param[in] off_set Point to the address in partition
*
* @return 0 : On success, others : On fail
*/
int hal_flash_markbad(hal_partition_t in_partition, uint32_t off_set);
/**
* Get the page size for nand
*
* @return page size
*/
uint32_t hal_flash_get_pgsize();
/**
* Get the block size for nand
*
* @return block size
*/
uint32_t hal_flash_get_blksize();
/**
* Write data to an area on a flash logical partition without erase
*
* @param[in] in_partition The target flash logical partition which should be read which should be written
* @param[in] off_set Point to the start address that the data is written to, and
* point to the last unwritten address after this function is
* returned, so you can call this function serval times without
* update this start address.
* @param[in] data_buf point to the data buffer that will be written to flash
* @param[in] data_buf_len The length of the data buffer
* @param[in] spare_buf point to the spare data buffer that will be written to flash
* @param[in] spare_buf_len The length of the spare buffer
*
* @return 0 : On success, EIO : If an error occurred with any step
*/
int32_t hal_flash_write_with_spare(hal_partition_t in_partition, uint32_t *off_set,
const void *data_buf, uint32_t data_buf_len,
const void *spare_buf, uint32_t spare_buf_len);
/**
* Read data (with spare) from an area on a Flash to data buffer in RAM,
*
* @param[in] in_partition The target flash logical partition which should be read
* @param[in] off_set Point to the start address that the data is read, and
* point to the last unread address after this function is
* returned, so you can call this function serval times without
* update this start address.
* @param[in] data_buf Point to the data buffer that stores the data read from flash
* @param[in] data_buf_len The length of the data buffer
* @param[in] spare_buf Point to the spare data buffer that stores the data read from flash
* @param[in] spare_buf_len The length of the spare buffer
*
* @return 0 : On success, EIO : If an error occurred with any step
*/
int32_t hal_flash_read_with_spare(hal_partition_t in_partition, uint32_t *off_set,
void *data_buf, uint32_t data_buf_len,
void *spare_buf, uint32_t spare_buf_len);
#endif /* _NAND_FLASH_HAL_ */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/hal/nand_flash.h | C | apache-2.0 | 5,430 |
/**
* @file nor.h
* @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef HAL_NOR_H
#define HAL_NOR_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup hal_nor NOR
* nor hal API.
*
* @{
*/
#include <stdint.h>
typedef struct {
uint32_t block_size; /**< NOR memory block size number of bytes */
uint32_t chip_size; /**< NOR memory chip size measured in number of blocks */
} nor_config_t;
typedef struct {
uint32_t base_addr; /**< NOR memory base address */
nor_config_t config; /**< NOR memory config args */
void *priv; /**< NOR memory priv args */
} nor_dev_t;
/**
* Initialises a nor flash interface
*
* @param[in] nor the interface which should be initialised
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nor_init(nor_dev_t *nor);
/**
* Deinitialises a nor flash interface
*
* @param[in] nand the interface which should be Deinitialised
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nor_finalize(nor_dev_t *nor);
/**
* Read data from NOR memory
*
* @param[in] nor the interface which should be initialised
* @param[out] data pointer to the buffer which will store incoming data
* @param[in] addr nor memory address
* @param[in] len the number of bytes to read
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nor_read(nor_dev_t *nor, uint32_t *addr, uint8_t *data, uint32_t len);
/**
* Write data to NOR memory
*
* @param[in] nor the interface which should be Writed to
* @param[in] data pointer to source buffer to write
* @param[in] addr nor memory address
* @param[in] len the number of bytes to write
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nor_write(nor_dev_t *nor, uint32_t *addr, uint8_t *data, uint32_t len);
/*
* Erase the blocks of the NOR memory
*
* @param[in] nor the interface which should be Erased
* @param[in] addr nor memory address
* @param[in] block_count the number of block to erase
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nor_erase_block(nor_dev_t *nor, uint32_t *addr, uint32_t block_count);
/*
* Erase the entire NOR chip
*
* @param[in] nor the interface which should be Erased
* @param[in] addr nor memory address
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_nor_erase_chip(nor_dev_t *nor, uint32_t *addr);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* HAL_NOR_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/hal/nor.h | C | apache-2.0 | 2,518 |
/**
* @file rng.h
* @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef HAL_RNG_H
#define HAL_RNG_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup hal_rng RNG
* rng hal API.
*
* @{
*/
#include <stdint.h>
typedef struct {
uint8_t port; /**< random device port */
void *priv; /**< priv data */
} random_dev_t;
/**
* Fill in a memory buffer with random data
*
* @param[in] random the random device
* @param[out] inBuffer Point to a valid memory buffer, this function will fill
* in this memory with random numbers after executed
* @param[in] inByteCount Length of the memory buffer (bytes)
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_random_num_read(random_dev_t random, void *buf, int32_t bytes);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* HAL_RNG_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/hal/rng.h | C | apache-2.0 | 890 |
/**
* @file rtc.h
* @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef HAL_RTC_H
#define HAL_RTC_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup hal_rtc RTC
* rtc hal API.
*
* @{
*/
#include <stdint.h>
/* Decode format list */
#define HAL_RTC_FORMAT_DEC 1
#define HAL_RTC_FORMAT_BCD 2
typedef struct {
uint8_t format; /**< time formart DEC or BCD */
} rtc_config_t;
typedef struct {
uint8_t port; /**< rtc port */
rtc_config_t config; /**< rtc config */
void *priv; /**< priv data */
} rtc_dev_t;
/*
* RTC time
*/
typedef struct {
uint8_t sec; /**< DEC format:value range from 0 to 59, BCD format:value range from 0x00 to 0x59 */
uint8_t min; /**< DEC format:value range from 0 to 59, BCD format:value range from 0x00 to 0x59 */
uint8_t hr; /**< DEC format:value range from 0 to 23, BCD format:value range from 0x00 to 0x23 */
uint8_t weekday; /**< DEC format:value range from 1 to 7, BCD format:value range from 0x01 to 0x07 */
uint8_t date; /**< DEC format:value range from 1 to 31, BCD format:value range from 0x01 to 0x31 */
uint8_t month; /**< DEC format:value range from 1 to 12, BCD format:value range from 0x01 to 0x12 */
uint16_t year; /**< DEC format:value range from 0 to 9999, BCD format:value range from 0x0000 to 0x9999 */
} rtc_time_t;
/**
* This function will initialize the on board CPU real time clock
*
*
* @param[in] rtc rtc device
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_rtc_init(rtc_dev_t *rtc);
/**
* This function will return the value of time read from the on board CPU real time clock.
*
* @param[in] rtc rtc device
* @param[out] time pointer to a time structure
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_rtc_get_time(rtc_dev_t *rtc, rtc_time_t *time);
/**
* This function will set MCU RTC time to a new value.
*
* @param[in] rtc rtc device
* @param[in] time pointer to a time structure
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_rtc_set_time(rtc_dev_t *rtc, const rtc_time_t *time);
/**
* De-initialises an RTC interface, Turns off an RTC hardware interface
*
* @param[in] RTC the interface which should be de-initialised
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_rtc_finalize(rtc_dev_t *rtc);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* HAL_RTC_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/hal/rtc.h | C | apache-2.0 | 2,460 |
/**
* @file sd.h
* @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef HAL_SD_H
#define HAL_SD_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup hal_sd SD
* sd hal API.
*
* @{
*/
#include <stdint.h>
/* This enum lists all SD states */
typedef enum {
SD_STAT_RESET,
SD_STAT_READY,
SD_STAT_TIMEOUT,
SD_STAT_BUSY,
SD_STAT_PROGRAMMING,
SD_STAT_RECEIVING,
SD_STAT_TRANSFER,
SD_STAT_ERR
} hal_sd_stat;
/* Define sd blk info */
typedef struct {
uint32_t blk_nums; /**< sd total block nums */
uint32_t blk_size; /**< sd block size */
} hal_sd_info_t;
/*
* UART configuration
*/
typedef struct {
uint32_t bus_wide; /**< sd bus wide */
uint32_t freq; /**< sd freq */
} sd_config_t;
/* Define sd dev handle */
typedef struct {
uint8_t port; /**< sd port */
sd_config_t config; /**< sd config */
void *priv; /**< priv data */
} sd_dev_t;
/**
* Initialises a sd interface
*
* @param[in] sd the interface which should be initialised
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_sd_init(sd_dev_t *sd);
/**
* Read sd blocks
*
* @param[in] sd the interface which should be read
* @param[out] data pointer to the buffer which will store incoming data
* @param[in] blk_addr sd blk addr
* @param[in] blks sd blks
* @param[in] timeout timeout in milisecond
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_sd_blks_read(sd_dev_t *sd, uint8_t *data, uint32_t blk_addr,
uint32_t blks, uint32_t timeout);
/**
* Write sd blocks
*
* @param[in] sd the interface which should be wrote
* @param[in] data pointer to the buffer which will store incoming data
* @param[in] blk_addr sd blk addr
* @param[in] blks sd blks
* @param[in] timeout timeout in milisecond
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_sd_blks_write(sd_dev_t *sd, uint8_t *data, uint32_t blk_addr,
uint32_t blks, uint32_t timeout);
/**
* Erase sd blocks
*
* @param[in] sd the interface which should be erased
* @param[in] blk_start_addr sd blocks start addr
* @param[in] blk_end_addr sd blocks end addr
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_sd_erase(sd_dev_t *sd, uint32_t blk_start_addr, uint32_t blk_end_addr);
/**
* Get sd state
*
* @param[in] sd the interface which should be got state
* @param[out] stat pointer to the buffer which will store incoming state data
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_sd_stat_get(sd_dev_t *sd, hal_sd_stat *stat);
/**
* Get sd info
*
* @param[in] sd the interface which should be got info
* @param[out] stat pointer to the buffer which will store incoming info data
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_sd_info_get(sd_dev_t *sd, hal_sd_info_t *info);
/**
* Deinitialises a sd interface
*
* @param[in] sd the interface which should be Deinitialised
*
* @return 0 : on success, otherwise is error
*/
int32_t hal_sd_finalize(sd_dev_t *sd);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* HAL_SD_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/hal/sd.h | C | apache-2.0 | 3,247 |
/**
* @file usbd.h
* @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef HAL_USBD_H
#define HAL_USBD_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup hal_usbd USBD
* usbd hal API.
*
* @{
*/
#include <stdint.h>
#include "usb_device.h"
/* Endpoint transfer status, for endpoints > 0 */
typedef enum {
EP_COMPLETED, /**< Transfer completed */
EP_PENDING, /**< Transfer in progress */
EP_INVALID, /**< Invalid parameter */
EP_STALLED, /**< Endpoint stalled */
} ep_status;
/* Initialization */
/******************************************************************************************/
/**
* @brief Initialize usb device driver
*
* @param[in] pdev point to usb device handler
*
* @return the operation status, USBD_OK is OK, USBD_BUSY is BUSY, others is error
*/
usbd_stat_t usbd_hal_init(void *pdev);
/**
* @brief Deinitialize usb device driver
*
* @param[in] pdev point to usb device handler
*
* @return the operation status, USBD_OK is OK, USBD_BUSY is BUSY, others is error
*/
usbd_stat_t usbd_hal_deinit(void *pdev);
/**
* @brief start usb device driver
*
* @param[in] pdev point to usb device handler
*
* @return the operation status, USBD_OK is OK, USBD_BUSY is BUSY, others is error
*/
usbd_stat_t usbd_hal_start(void *pdev);
/**
* @brief stop usb device driver
*
* @param[in] pdev point to usb device handler
*
* @return the operation status, USBD_OK is OK, USBD_BUSY is BUSY, others is error
*/
usbd_stat_t usbd_hal_stop(void *pdev);
/**
* @brief enable usb device interrupt
*/
void usbd_hal_connect(void);
/**
* @brief disable usb device interrupt
*/
void usbd_hal_disconnect(void);
/**
* @brief configure usb device info
*/
void usbd_hal_configure_device(void);
/**
* @brief unconfigure usb device info
*/
void usbd_hal_unconfigure_device(void);
/**
* @brief set usb device address
*
* @param[in] pdev point to usb device handler
* @param[in] address the usb device address
*
* @return none
*/
void usbd_hal_set_address(void *pdev, uint8_t address);
/* Endpoint 0 */
/******************************************************************************************/
/**
* @brief Endpoint0 setup(read setup packet)
*
* @param[in] buffer point to usb device handler
*
* @return none
*/
void usbd_hal_ep0_setup(uint8_t *buffer);
/**
* @brief Endpoint0 read packet
*
* @param[in] pdev point to usb device handler
*
* @return none
*/
void usbd_hal_ep0_read(void *pdev);
/**
* @brief Endpoint0 read stage
*/
void usbd_hal_ep0_read_stage(void);
/**
* @brief Endpoint0 get read result
*
* @param[in] pdev point to usb device handler
* @param[out] buffer point to packet
*
* @return the length of read packet
*/
uint32_t usbd_hal_get_ep0_read_result(void *pdev, uint8_t *buffer);
/**
* @brief Endpoint0 write
*
* @param[in] pdev point to usb device handler
* @param[in] buffer point to packet
* @param[in] size the length of write packet
*
* @return none
*/
void usbd_hal_ep0_write(void *pdev, uint8_t *buffer, uint32_t size);
/**
* @brief Get endpoint0 write result
*/
void usbd_hal_get_ep0_write_result(void);
/**
* @brief Stall endpoint0
*
* @param[in] pdev point to usb device handler
*
* @return none
*/
void usbd_hal_ep0_stall(void *pdev);
/* Other endpoints */
/******************************************************************************************/
/**
* @brief open the endpoint
*
* @param[in] pdev point to usb device handler
* @param[in] endpoint the num of endpoint
* @param[in] maxPacket the max size of packet
* @param[in] flags options flags for configuring endpoints
*
* @return true is ok, false is fail
*/
bool usbd_hal_realise_endpoint(void *pdev, uint8_t endpoint, uint32_t maxPacket, uint32_t flags);
/**
* @brief start read the endpoint data
*
* @param[in] pdev point to usb device handler
* @param[in] endpoint the num of endpoint
* @param[in] maximumSize amount of data to be received
*
* @return endpoint status
*/
ep_status usbd_hal_endpoint_read(void *pdev, uint8_t endpoint, uint32_t maximumSize);
/**
* @brief read the endpoint data
*
* @param[in] pdev point to usb device handler
* @param[in] endpoint the num of endpoint
* @param[out] data point to receive buffer
* @param[out] bytesRead amount of data be received
*
* @return endpoint status
*/
ep_status usbd_hal_endpoint_read_result(void *pdev, uint8_t endpoint, uint8_t *data, uint32_t *bytesRead);
/**
* @brief start write the endpoint data
*
* @param[in] pdev point to usb device handler
* @param[in] endpoint the num of endpoint
* @param[in] data point to write buffer
* @param[in] size amount of data to be write
*
* @return endpoint status
*/
ep_status usbd_hal_endpoint_write(void *pdev, uint8_t endpoint, uint8_t *data, uint32_t size);
/**
* @brief get writting endpoint data status
*
* @param[in] pdev point to usb device handler
* @param[in] endpoint the num of endpoint
*
* @return endpoint status
*/
ep_status usbd_hal_endpoint_write_result(void *pdev, uint8_t endpoint);
/**
* @brief stall the endpoint
*
* @param[in] pdev point to usb device handler
* @param[in] endpoint the num of endpoint
*
* @return none
*/
void usbd_hal_stall_endpoint(void *pdev, uint8_t endpoint);
/**
* @brief unstall the endpoint
*
* @param[in] pdev point to usb device handler
* @param[in] endpoint the num of endpoint
*
* @return none
*/
void usbd_hal_unstall_endpoint(void *pdev, uint8_t endpoint);
/**
* @brief get the endpoint status of stall
*
* @param[in] pdev point to usb device handler
* @param[in] endpoint the num of endpoint
*
* @return true is ok, false is false
*/
bool usbd_hal_get_endpoint_stall_state(void *pdev, uint8_t endpoint);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* HAL_USBD_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/hal/usbd.h | C | apache-2.0 | 5,964 |
/**
* @file usbh.h
* @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef HAL_USBH_H
#define HAL_USBH_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup hal_usbh USBH
* usbh hal API.
*
* @{
*/
#include <stdint.h>
/**
* @brief Initialize The USB Host Controller
*
* @param[in] phost pointer to the usb host handler
* @param[out] phcd pointer to the usb hcd driver pointer
*
* @return 0:success, otherwise is failed
*/
int hal_usbh_init(void *phost, void **phcd);
/**
* @brief Finalize The USB Host Controller
*
* @param[in] hcd pointer to the usb hcd
*
* @return 0:success, otherwise is failed
*/
int hal_usbh_finalize(void *hcd);
/**
* @brief Reset Host Controller's Port
*
* @param[in] hcd pointer to the usb hcd
*
* @return 0:success, otherwise is failed
*/
int hal_usbh_port_reset(void *hcd);
/**
* @brief Get Device Speed
*
* @param[in] hcd pointer to the usb hcd
*
* @return the usb host controller's speed
* (0:USB_PORT_SPEED_LOW, 1:USB_PORT_SPEED_FULL, 2:USB_PORT_SPEED_HIGH)
*/
int hal_usbh_get_speed(void *hcd);
/**
* @brief Free The Host Controll's Pipe
*
* @param[in] hcd pointer to the usb hcd
* @param[in] pipe_num the index of the pipe
*
* @return 0:success, otherwise is failed
*/
int hal_usbh_pipe_free(void *hcd, uint8_t pipe_num);
/**
* @brief Configure The Host Controller's Pipe
*
* @param[in] hcd pointer to the usb hcd
* @param[in] index the index of the pipe
* @param[in] ep_addr the endpoint address
* @param[in] dev_addr the device address
* @param[in] speed the device speed
* @param[in] token the transmit PID token
* @param[in] ep_type the endpoint type
* @param[in] mps the max packet size per transmit
*
* @return 0:success, otherwise is failed
*/
int hal_usbh_pipe_configure(void *hcd, uint8_t index, uint8_t ep_addr, uint8_t dev_addr,
uint8_t speed, uint8_t ep_type, uint16_t mps);
/**
* @brief Submit The Urb, start to send or receive data
*
* @param[in] hcd pointer to the usb hcd
* @param[in] pipe_num the index of the pipe
* @param[in] direction the transmit direction
* @param[in] ep_type the endpoint type
* @param[in] token the transmit token
* @param[in/out] buf pointer to the buffer which will be send or recv
* @param[in] length the length of buffer
*
* @return 0:success, otherwise is failed
*/
int hal_usbh_submit_urb(void *hcd, uint8_t pipe_num, uint8_t direction, uint8_t ep_type,
uint8_t token, uint8_t *buf, uint16_t length);
/**
* @brief Get The Urb Transmit State
*
* @param[in] hcd pointer to the usb hcd
* @param[in] pipe_num the index of the pipe
*
* @return 0:Idle, 1:Done, 2:Not Ready, 3:Nyet, 4:Error, 5:Stall
*/
int hal_usbh_get_urb_state(void *hcd, uint8_t pipe_num);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* HAL_USBH_H */
| YifuLiu/AliOS-Things | components/drivers/core/base/include/aos/hal/usbh.h | C | apache-2.0 | 2,985 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _DEVICE_VFS_H_
#define _DEVICE_VFS_H_
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <aos/kernel.h>
#include <drivers/mutex.h>
#include <drivers/u_ld.h>
#include <drivers/platform/u_platform_bus.h>
#define __weak __attribute__((weak))
#ifndef USER_SPACE_DRIVER
static inline void *aos_ipc_copy(void *dst, void *src, size_t len) {
memcpy(dst, src, len);
return dst;
}
#endif
/**
* subsys device type list
*/
enum SUBSYS_BUS_TYPE {
BUS_TYPE_PLATFORM,
BUS_TYPE_SPI,
BUS_TYPE_I2C,
BUS_TYPE_USB,
BUS_TYPE_SDIO,
BUS_TYPE_MAX
};
typedef struct file_ops subsys_file_ops_t;
/**
* type and name are mandaotry, type is set to BUS_TYPE_PLATFORM if no bus is defined in "enum SUBSYS_BUS_TYPE"
* delay_init should be set to 1 if the application scenario is time sensitive
* if delay_init is set to true
* * subsys_drv's init/probe won't be called during driver init procedure;
* * init/probe will be called only when open request comes
*/
struct subsys_dev {
int permission;
bool delay_init;
enum SUBSYS_BUS_TYPE type;
void *user_data;
char *node_name;
};
/**
* drv_name - subsystem driver name
*
* here we provide 2 ind of driver ops:
* 1. legacy driver API - for legacy rtos driver ops
* 2. linux-like drivers - for drivers' written with concept of Linux
* user can select either 1st or 2nd way, when both ops sets are provided, legacy driver will be used
*
* init - driver's initialization function callback, this API is called only once per device
* deinit - driver's deinitialization function callback, this API is called only when device is removed when calling aos_dev_unreg
* pm - for power managerment function
*
* probe - same function as init
* remove - same function as deinit
* shutdown/suspend/resume - power management related behavior's API
*/
struct subsys_drv {
char *drv_name;
/* for legacy drivers */
int (*init)(struct u_platform_device *_dev);
int (*deinit)(struct u_platform_device *_dev);
int (*pm)(struct u_platform_device *dev, u_pm_ops_t state);
/* for linux-like drivers */
int (*probe)(struct u_platform_device *);
int (*remove)(struct u_platform_device *);
void (*shutdown)(struct u_platform_device *);
int (*suspend)(struct u_platform_device *, int /*pm_message_t */state);
int (*resume)(struct u_platform_device *);
};
/**
*
* register devices and corresponding driver into device/driver module
*
* @param sdev - device identifier, name and type must be carefully set
* @param sfops - file operations API
* @param sdrv - device driver operations callback
* - init/probe will be called when device exist
* - deinit/remove will be called when aos_dev_unreg is called
* @return 0 if device register success; return negative error no. if device register fails
*/
int aos_dev_reg(struct subsys_dev *sdev, subsys_file_ops_t *sfops, struct subsys_drv* sdrv);
/**
* This function is not used for the moment
* register remote devices/driver into device/driver module, only support rpc mode
*
* @param sdev - device identifier, name and type must be carefully set
* @param sfops - file operations API
* @param sdrv - device driver operations callback
* - probe will be called when device exist
* - remove will be called when aos_dev_unreg is called
* @return 0 if device register success; return negative error no. if device register fails
*/
int aos_remote_dev_reg(struct subsys_dev *sdev, subsys_file_ops_t *sfops, struct subsys_drv* sdrv);
/**
*
* register device array
*
* @param sdev pointer to devices array be register
* @param size device array size
* @param sfops file operations API
* @param sdrv - device driver operations callback
* - probe will be called when device exist
* - remove will be called when aos_dev_unreg is called
* @return 0 for success; negative for failure
*/
int aos_devs_reg(struct subsys_dev *sdev[], int size, subsys_file_ops_t *sfops, struct subsys_drv* sdrv);
/**
* unregister device driver
*
* @param sdev - device identifier, name and type must be carefully set
*
* @return 0 if device register success; return negative error no. if device register fails
*/
int aos_dev_unreg(struct subsys_dev *sdev);
/**
* unregister device array
*
* @param sdev - pointer to devices array be register
* @param size - device array size
*
* @return 0 if device register success; return negative error no. if device register fails
*/
int aos_devs_unreg(struct subsys_dev *sdev[], int size);
#endif //_DEVICE_VFS_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/devicevfs/devicevfs.h | C | apache-2.0 | 4,724 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _DEVICEVFS_RPC_H_
#define _DEVICEVFS_RPC_H_
/**
*
* open RPC message handler, called when OPEN rpc message arrived in main rpc service's handler
*
* @param parg - pointer to u_fops_arg_u
* @param crpc_handle - rpc client's handle,
* response should be send to rpc client no matter this operation succeed or not
*
* @return 0 for success; negative for failure
*/
int u_device_rpc_open(u_fops_arg_u *parg, int crpc_handle);
/**
* close RPC message handler, called when CLOSE rpc message arrived in main rpc service's handler
*
* @param parg - pointer to u_fops_arg_u
* @param crpc_handle - rpc client's handle,
* response should be send to rpc client no matter this operation succeed or not
*
* @return 0 for success; negative for failure
*/
int u_device_rpc_close(u_fops_arg_u *parg, int crpc_handle);
#endif //_DEVICEVFS_RPC_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/devicevfs/devicevfs_rpc.h | C | apache-2.0 | 921 |
/* atomic operations */
/*
* Copyright (c) 1997-2015, Wind River Systems, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __ATOMIC_H__
#define __ATOMIC_H__
#ifdef __cplusplus
static "C" {
#endif
typedef int atomic_t;
typedef atomic_t atomic_val_t;
/**
* @defgroup atomic_apis Atomic Services APIs
* @ingroup kernel_apis
* @{
*/
/**
* @brief Atomic compare-and-set.
*
* This routine performs an atomic compare-and-set on @a target. If the current
* value of @a target equals @a old_value, @a target is set to @a new_value.
* If the current value of @a target does not equal @a old_value, @a target
* is left unchanged.
*
* @param target Address of atomic variable.
* @param old_value Original value to compare against.
* @param new_value New value to store.
* @return 1 if @a new_value is written, 0 otherwise.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline int atomic_cas(atomic_t *target, atomic_val_t old_value,
atomic_val_t new_value)
{
return __atomic_compare_exchange_n(target, &old_value, new_value,
0, __ATOMIC_SEQ_CST,
__ATOMIC_SEQ_CST);
}
#else
int atomic_cas(atomic_t *target, atomic_val_t old_value,
atomic_val_t new_value);
#endif
/**
*
* @brief Atomic addition.
*
* This routine performs an atomic addition on @a target.
*
* @param target Address of atomic variable.
* @param value Value to add.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_add(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_add(target, value, __ATOMIC_SEQ_CST);
}
#else
atomic_val_t atomic_add(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic subtraction.
*
* This routine performs an atomic subtraction on @a target.
*
* @param target Address of atomic variable.
* @param value Value to subtract.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_sub(target, value, __ATOMIC_SEQ_CST);
}
#else
atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic increment.
*
* This routine performs an atomic increment by 1 on @a target.
*
* @param target Address of atomic variable.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_inc(atomic_t *target)
{
return atomic_add(target, 1);
}
#else
atomic_val_t atomic_inc(atomic_t *target);
#endif
/**
*
* @brief Atomic decrement.
*
* This routine performs an atomic decrement by 1 on @a target.
*
* @param target Address of atomic variable.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_dec(atomic_t *target)
{
return atomic_sub(target, 1);
}
#else
atomic_val_t atomic_dec(atomic_t *target);
#endif
/**
*
* @brief Atomic get.
*
* This routine performs an atomic read on @a target.
*
* @param target Address of atomic variable.
*
* @return Value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_get(const atomic_t *target)
{
return __atomic_load_n(target, __ATOMIC_SEQ_CST);
}
#else
atomic_val_t atomic_get(const atomic_t *target);
#endif
/**
*
* @brief Atomic get-and-set.
*
* This routine atomically sets @a target to @a value and returns
* the previous value of @a target.
*
* @param target Address of atomic variable.
* @param value Value to write to @a target.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_set(atomic_t *target, atomic_val_t value)
{
/* This builtin, as described by Intel, is not a traditional
* test-and-set operation, but rather an atomic exchange operation. It
* writes value into *ptr, and returns the previous contents of *ptr.
*/
return __atomic_exchange_n(target, value, __ATOMIC_SEQ_CST);
}
#else
atomic_val_t atomic_set(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic clear.
*
* This routine atomically sets @a target to zero and returns its previous
* value. (Hence, it is equivalent to atomic_set(target, 0).)
*
* @param target Address of atomic variable.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_clear(atomic_t *target)
{
return atomic_set(target, 0);
}
#else
atomic_val_t atomic_clear(atomic_t *target);
#endif
/**
*
* @brief Atomic bitwise inclusive OR.
*
* This routine atomically sets @a target to the bitwise inclusive OR of
* @a target and @a value.
*
* @param target Address of atomic variable.
* @param value Value to OR.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_or(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_or(target, value, __ATOMIC_SEQ_CST);
}
#else
atomic_val_t atomic_or(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic bitwise exclusive OR (XOR).
*
* This routine atomically sets @a target to the bitwise exclusive OR (XOR) of
* @a target and @a value.
*
* @param target Address of atomic variable.
* @param value Value to XOR
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_xor(target, value, __ATOMIC_SEQ_CST);
}
#else
atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic bitwise AND.
*
* This routine atomically sets @a target to the bitwise AND of @a target
* and @a value.
*
* @param target Address of atomic variable.
* @param value Value to AND.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_and(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_and(target, value, __ATOMIC_SEQ_CST);
}
#else
atomic_val_t atomic_and(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic bitwise NAND.
*
* This routine atomically sets @a target to the bitwise NAND of @a target
* and @a value. (This operation is equivalent to target = ~(target & value).)
*
* @param target Address of atomic variable.
* @param value Value to NAND.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_nand(target, value, __ATOMIC_SEQ_CST);
}
#else
atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value);
#endif
/**
* @brief Initialize an atomic variable.
*
* This macro can be used to initialize an atomic variable. For example,
* @code atomic_t my_var = ATOMIC_INIT(75); @endcode
*
* @param i Value to assign to atomic variable.
*/
#define ATOMIC_INIT(i) (i)
/**
* @cond INTERNAL_HIDDEN
*/
#define ATOMIC_BITS (sizeof(atomic_val_t) * 8)
#define ATOMIC_MASK(bit) (1 << ((bit) & (ATOMIC_BITS - 1)))
#define ATOMIC_ELEM(addr, bit) ((addr) + ((bit) / ATOMIC_BITS))
/**
* INTERNAL_HIDDEN @endcond
*/
/**
* @brief Define an array of atomic variables.
*
* This macro defines an array of atomic variables containing at least
* @a num_bits bits.
*
* @note
* If used from file scope, the bits of the array are initialized to zero;
* if used from within a function, the bits are left uninitialized.
*
* @param name Name of array of atomic variables.
* @param num_bits Number of bits needed.
*/
#define ATOMIC_DEFINE(name, num_bits) \
atomic_t name[1 + ((num_bits) - 1) / ATOMIC_BITS]
/**
* @brief Atomically test a bit.
*
* This routine tests whether bit number @a bit of @a target is set or not.
* The target may be a single atomic variable or an array of them.
*
* @param target Address of atomic variable or array.
* @param bit Bit number (starting from 0).
*
* @return 1 if the bit was set, 0 if it wasn't.
*/
static inline int atomic_test_bit(const atomic_t *target, int bit)
{
atomic_val_t val = atomic_get(ATOMIC_ELEM(target, bit));
return (1 & (val >> (bit & (ATOMIC_BITS - 1))));
}
/**
* @brief Atomically test and clear a bit.
*
* Atomically clear bit number @a bit of @a target and return its old value.
* The target may be a single atomic variable or an array of them.
*
* @param target Address of atomic variable or array.
* @param bit Bit number (starting from 0).
*
* @return 1 if the bit was set, 0 if it wasn't.
*/
static inline int atomic_test_and_clear_bit(atomic_t *target, int bit)
{
atomic_val_t mask = ATOMIC_MASK(bit);
atomic_val_t old;
old = atomic_and(ATOMIC_ELEM(target, bit), ~mask);
return (old & mask) != 0;
}
/**
* @brief Atomically set a bit.
*
* Atomically set bit number @a bit of @a target and return its old value.
* The target may be a single atomic variable or an array of them.
*
* @param target Address of atomic variable or array.
* @param bit Bit number (starting from 0).
*
* @return 1 if the bit was set, 0 if it wasn't.
*/
static inline int atomic_test_and_set_bit(atomic_t *target, int bit)
{
atomic_val_t mask = ATOMIC_MASK(bit);
atomic_val_t old;
old = atomic_or(ATOMIC_ELEM(target, bit), mask);
return (old & mask) != 0;
}
/**
* @brief Atomically clear a bit.
*
* Atomically clear bit number @a bit of @a target.
* The target may be a single atomic variable or an array of them.
*
* @param target Address of atomic variable or array.
* @param bit Bit number (starting from 0).
*
* @return N/A
*/
static inline void atomic_clear_bit(atomic_t *target, int bit)
{
atomic_val_t mask = ATOMIC_MASK(bit);
atomic_and(ATOMIC_ELEM(target, bit), ~mask);
}
/**
* @brief Atomically set a bit.
*
* Atomically set bit number @a bit of @a target.
* The target may be a single atomic variable or an array of them.
*
* @param target Address of atomic variable or array.
* @param bit Bit number (starting from 0).
*
* @return N/A
*/
static inline void atomic_set_bit(atomic_t *target, int bit)
{
atomic_val_t mask = ATOMIC_MASK(bit);
atomic_or(ATOMIC_ELEM(target, bit), mask);
}
/**
*
* @brief Atomic subtraction and test
*
* This routine performs an atomic subtraction on @a target.
*
* @param target Address of atomic variable.
* @param value Value to subtract.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline int atomic_sub_and_test (int i, atomic_t *target)
{
return __sync_sub_and_fetch(target, i, __ATOMIC_SEQ_CST) == i ? 1 : 0;
}
#else
int atomic_sub_and_test (int i, atomic_t *target);
#endif
/**
*
* @brief Atomic subtraction and test
*
* This routine performs an atomic subtraction on @a target.
*
* @param target Address of atomic variable.
* @param value Value to subtract.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline int atomic_dec_return (atomic_t *target)
{
return __sync_sub_and_fetch(target, 1, __ATOMIC_SEQ_CST);
}
#else
int atomic_dec_return (atomic_t *target);
#endif
/**
*
* @brief Atomic addition and return
*
* This routine performs an atomic addition on @a target.
*
* @param target Address of atomic variable.
* @param value Value to add.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline int atomic_inc_return (atomic_t *target)
{
return __sync_add_and_fetch(target, 1, __ATOMIC_SEQ_CST);
}
#else
int atomic_inc_return (atomic_t *target);
#endif
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline int atomic_read (atomic_t *target)
{
return atomic_get(target);
}
#else
int atomic_read (atomic_t *target);
#endif
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif //__ATOMIC_H__
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/atomic.h | C | apache-2.0 | 11,832 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _BUG_H_
#define _BUG_H_
#include <stdio.h>
#define BUG() do {} while(1)
#define panic(...) BUG_ON_MSG(1, ##__VA_ARGS__)
#define BUG_ON(condition) do { \
if (unlikely(condition)) { \
printf("BUG at %s:%d!\r\n", __func__, __LINE__); \
BUG(); \
} \
} while (0)
#define BUG_ON_MSG(condition, fmt, ...) do { \
if(condition) { \
printf("BUG at %s:%d! "fmt"\r\n", __func__, __LINE__, ##__VA_ARGS__); \
} \
} while (0)
#define WARN_ON(condition) ({\
int __ret = !!(condition); \
if(__ret) { \
printf("WARN at %s:%d!\r\n", __func__, __LINE__); \
} \
__ret;})
#define WARN_ON_ONCE(condition) ({\
static int __ret = 0; \
__ret = !!(condition); \
if(__ret) { \
printf("WARN at %s:%d!\r\n", __func__, __LINE__); \
} \
__ret;})
#define WARN(condition, fmt, ...) ({\
static int __ret = 0; \
__ret = !!(condition); \
if(__ret) { \
printf("WARN at %s:%d "fmt"\r\n", __func__, __LINE__, ##__VA_ARGS__); \
} \
__ret;})
#define WARN_ON_MSG(condition, fmt, ...) do { \
if(condition) { \
printf("WARN at %s:%d! "fmt"\r\n", __func__, __LINE__, ##__VA_ARGS__); \
} \
} while (0)
#define BUILD_BUG_ON(condition) BUG_ON(condition)
#endif //_BUG_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/bug.h | C | apache-2.0 | 1,247 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _U_BUS_H_
#define _U_BUS_H_
#include "aos/list.h"
#include <drivers/spinlock.h>
#include <drivers/char/u_driver.h>
/**
* struct u_bus_private - bus private information
* should only be accessed by char_core
* @dev_list: device list belongs to current bus
* @drv_list: driver list belongs to current bus
* @bus: pointer to the bus struct this u_bus_private_t belongs to
*
* */
typedef struct u_bus_private {
spinlock_t lock;
struct dlist_s dev_list;
struct dlist_s drv_list;
struct dlist_s bus_node;
struct u_bus *bus;
} u_bus_private_t;
/**
* struct u_bus - bus struct, virtual or hardware bus
*
* @name: bus name
* @drv_list: driver list belongs to this bus
* @match:
* @probe:
* @remove:
* @shutdown:
* @online:
* @offline:
* @suspend:
* @resume:
* @on_ping:
* @pm:
*
* */
typedef struct u_bus {
char *name;
struct u_bus_private *p;
// for legacy drivers
int (*init)(struct u_device *_dev);
int (*deinit)(struct u_device *_dev);
int (*pm)(struct u_device *dev, u_pm_ops_t state);
int (*match)(struct u_device *dev, struct u_driver *drv);
// for linux-like drivers
int (*probe)(struct u_device *dev);
int (*remove)(struct u_device *dev);
void (*shutdown)(struct u_device *dev);
int (*online)(struct u_device *dev);
int (*offline)(struct u_device *dev);
int (*suspend)(struct u_device *dev, u_pm_ops_t state);
int (*resume)(struct u_device *dev);
// TODO: when receive IPC ping message call on_ping, shall move this to u_driver_private_t?
int (*on_ping)(struct u_device *dev);
} u_bus_t;
/**
* init global bus list
* */
int u_bus_init(void);
/**
* register bus to system
* @drv: the bus to register
*
* */
int u_bus_register(struct u_bus *bus);
/**
* unregister bus from system
* @drv: the bus to be removed
*
* */
int u_bus_unregister(struct u_bus *bus);
/**
* connect dev into target bus(dev->bus)
* low level operations, driver is not aware of this operation
*
* @param dev - pointer to target device
* @return always returns 0
*/
int u_bus_add_device(struct u_device *dev);
/**
* enumerate driver list and try to init the device with the drivers
*
* @param dev - pointer to the deviice to be initialized
*
* @return 0 if device initialization success; negative if device initialization fails
*/
int u_bus_try_init_device(struct u_device *dev);
/**
* add a driver into bus's driver list
*
* @param drv - the driver to be added
* @return always return 0
*/
int u_bus_add_driver(struct u_driver *drv);
/**
* get the bus with specified name
* @name: the name of target bus
*
* */
u_bus_t *u_bus_get_by_name(char *name);
/**
* disconnect device with its driver and delete it from target bus(dev->bus)
*
* @param dev - pointer to target device
* @return always return 0
*/
int u_bus_del_device(struct u_device *dev);
/**
* delete a driver from bus's driver list
*
* @param drv - pointer to the driver to be deleted
* @return always return 0
*/
int u_bus_del_driver(struct u_driver *drv);
/**
* attach a driver into bus's driver list,
* try to init free devices(not drived by any driver) if device is matchd
*
* @drv: the driver to be added
* @return always return 0
*/
int u_bus_attach_driver(struct u_driver *drv);
/**
* deattch a driver into bus's driver list
*
* @param drv - pointer to target driver to be deatched
* @return always return 0
*/
int u_bus_detach_driver(struct u_driver *drv);
#if 0
struct u_device *u_device_find_by_devid(dev_t devid);
#endif
#endif //_U_BUS_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/char/u_bus.h | C | apache-2.0 | 3,565 |
/**
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _CHAR_DEV_H_
#define _CHAR_DEV_H_
#include "aos/list.h"
#define CDEV_LOG_DEBUG 0
#define CDEV_LOG_INFO 1
#define CDEV_LOG_WARN 2
#define CDEV_LOG_ERROR 3
extern int g_cdev_log_level;
static char cdev_level_tag[] = {
'D',
'I',
'W',
'E'
};
#define cdev_log(level, format, ...) do { \
if (level >= g_cdev_log_level) \
printf("<%c> [%s:%u]" format, cdev_level_tag[level], __FUNCTION__, __LINE__, ##__VA_ARGS__); \
} while (0)
#define cdev_loud(format, ...) cdev_log(CDEV_LOG_DEBUG, format, ##__VA_ARGS__)
#define cdev_dbg(format, ...) cdev_log(CDEV_LOG_DEBUG, format, ##__VA_ARGS__)
#define cdev_info(format, ...) cdev_log(CDEV_LOG_INFO, format, ##__VA_ARGS__)
#define cdev_warn(format, ...) cdev_log(CDEV_LOG_WARN, format, ##__VA_ARGS__)
#define cdev_err(format, ...) cdev_log(CDEV_LOG_ERROR, format, ##__VA_ARGS__)
#ifndef MINORBITS
#define MINORBITS 20
#define MINORMASK ((1U << MINORBITS) - 1)
#define MAJOR(dev) ((unsigned int) ((dev) >> MINORBITS))
#define MINOR(dev) ((unsigned int) ((dev) & MINORMASK))
#define MKDEV(ma, mi) (((ma) << MINORBITS) | (mi))
#endif //MINORBITS
typedef struct u_cdev {
int dev_id;
unsigned int count;
dlist_t node;
const void *ops;
void *thread_ctx;
} u_cdev_t;
int u_cdev_module_init(void);
int u_cdev_init(u_cdev_t *dev, /*struct u_file_operations*/void *ops);
int u_cdev_add(u_cdev_t *dev, unsigned int devid, unsigned int count);
int u_cdev_del(u_cdev_t *dev);
int alloc_u_cdev_region(unsigned int *dev_id, unsigned int minor, unsigned int count);
int register_u_cdev_region(unsigned dev_id, unsigned count);
int __register_u_cdev_region(unsigned int major,
unsigned int minor,
int count);
int unregister_u_cdev_region(unsigned dev_id, unsigned count);
u_cdev_t * u_cdev_find_node_by_name(char *pathname);
u_cdev_t * u_cdev_find_node_by_devid(unsigned int devid);
#endif //_CHAR_DEV_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/char/u_cdev.h | C | apache-2.0 | 1,981 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _U_CDEV_MSG_H_
#define _U_CDEV_MSG_H_
#define U_CDEV_RPC_BUFFER_SIZE (4 * 1024 + 64)
typedef enum fops_msg_id {
FOPS_MIN = 0,
/* Application -> C */
FOPS_OPEN, /* open operation */
FOPS_READ, /* read operation */
FOPS_WRITE, /* write operation */
FOPS_IOCTL, /* ioctl operation */
FOPS_POLL, /* poll operation */
FOPS_LSEEK, /* lseek operation */
FOPS_CLOSE, /* close operation */
FOPS_MAX
} fops_msg_id_e;
typedef enum u_cdev_msg_id {
/* VFS<->char device */
CDEV_MSG_FOPS, /* file operation message id */
/* Others */
CDEV_MSG_LOOP,
CDEV_MSG_MAX
} u_cdev_msg_id_e;
#pragma pack(1)
/**
* file operation arguments
* open.flags: equeals to flags when calling open("path", flags)
* open.path: file's full pathname
* read.farg: equals to the open.arg in u_fops_result returned after open operation
* read.len: target length of the read operation
* write.farg: equals to the open.arg in u_fops_result returned after open operation
* write.len: target length of the write operation
* write.buf: the data to be write
* ioctl.farg: equals to the open.arg in u_fops_result returned after open operation
* ioctl.cmd: cmd equals to ioctl(fd, cmd, arg)
* ioctl.arg: arg equals to ioctl(fd, cmd, arg)
* poll.farg: equals to the open.arg in u_fops_result returned after open operation
* poll.flag: read/write flags
*/
typedef union u_fops_arg {
struct {
int flags;
char path[0];
} open;
struct {
void *farg;
int len;
} read;
struct {
void *farg;
int len;
char buf[0];
} write;
struct {
void *farg;
int cmd;
unsigned long arg;
} ioctl;
struct {
void *farg;
int flag;
} poll;
struct {
void *farg;
off_t off;
int whence;
} lseek;
struct {
void *farg;
} close;
struct {
void *farg;
} priv;
} u_fops_arg_u;
/**
* file ops result
* status: 0 means operation success
* open.farg: special pointer used in read/write/ioctl/poll operations
* read.len: the actual read bytes, while data is stored into read.data
* read.data: pointed to the buffer where the read data is stored
* write.len: actual length written to the file succefully
* poll.events: value of fd.events
*
*/
typedef union u_fops_result {
struct {
int status;
void *farg;
} open;
struct {
int status;
ssize_t len;
char data[0];
} read;
struct {
int status;
ssize_t len;
} write;
struct {
int status;
short events;
} poll;
struct {
int status;
off_t off;
} lseek;
struct {
int status;
} ioctl;
struct {
int status;
} close;
struct {
int status;
} priv;
} u_fops_result_u;
typedef struct u_cdev_msg_ie {
unsigned short t;
unsigned short l;
u_fops_arg_u v[0];
} u_cdev_msg_ie_t;
typedef u_cdev_msg_ie_t u_fops_ie_t;
/**
* struct dev_drv_msg - driver related IPC message format
* @msg_type: message
* */
typedef struct u_cdev_msg {
u_cdev_msg_id_e t;
unsigned short l;
u_cdev_msg_ie_t v[0];
} u_cdev_msg_t;
#pragma pack()
typedef int (*u_cdev_msg_handler)(int crpc_handle, u_cdev_msg_t *p_msg);
#define IE_FOR_EACH(p_msg) \
for (ie = (u_cdev_msg_ie_t *)p_msg->v; \
ie < (p_msg->v + sizeof(p_msg->l) + p_msg->l); \
ie = (u_cdev_msg_ie_t *)(ie->v + ie->l))
#endif //_U_CDEV_MSG_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/char/u_cdev_msg.h | C | apache-2.0 | 3,632 |
/**
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _U_DEVICE_H_
#define _U_DEVICE_H_
#include <stdio.h>
#include "aos/list.h"
#include "aos/vfs.h"
#include <drivers/spinlock.h>
#include <drivers/ddkc_log.h>
#define LOG_TAG "UDEV"
#include <ulog/ulog.h>
struct u_device;
struct u_device_private;
/* valid device id: [0, 9999), this should be very enough */
#define MAX_DEV_ID_DIGS 4
#define MAX_DEV_ID_NUM 9999
/**
* struct u_device_private - device private information
* should only be accessed by char_core
* @bus_node: node in bus list
* @driver_node: node in driver list
*
* */
typedef struct u_device_private {
spinlock_t lock;
struct dlist_s bus_node;
struct dlist_s drv_node;
struct dlist_s parent_node; /* node in parent's child list with head of child_head*/
struct dlist_s child_head; /* child list's head */
struct u_device *dev;
char *name;
} u_device_private_t;
/**
* struct u_device - device structure
* @parent: device's parent
* @drv: the driver by which this device is driven
* @bus: the bus to which this device is on
* @p: driver private information, device driver and bus list information
* */
typedef struct u_device {
struct u_device* parent;
struct u_driver *drv;
struct u_bus *bus;
char *name;
unsigned int id;
void *user_data;
void *driver_data;
unsigned int dev_id;
u_device_private_t *p;
} u_device_t;
/*
* all device node must be registered with u_device_node_create
* */
typedef struct u_dev_node {
//TODO: should add lock for device node list operation
struct dlist_s node;
struct u_dev_node *parent;
int dev_id;
//TODO: shall dev be added for device node?
struct u_device *dev;
char *path_name;
void *drv_data;
struct file_operations *fops;
struct file_ops legacy_fops;
char name[0];
} u_dev_node_t;
typedef struct u_device_info_ipc {
unsigned int id;
char name[32];
} u_device_info_ipc_t;
/**
* add device into bus device list
* conditions to check in u_device_add:
* 1. dev is not NULL
* 2. dev->bus is assigned correctly
* 3. dev->p is allocated and initialized
*
* @param dev - pointer to target device
* @return 0 for success; netative for failure
*/
int u_device_add(struct u_device *dev);
/**
* initialize u_device's private info
*
* @param dev - pointer to target device
* @return 0 for success; netative for failure
*/
int u_device_initialize(struct u_device *dev);
/**
* register a device into system
*
* @param dev - pointer to target device
* @return 0 for success; netative for failure
*/
int u_device_register(struct u_device *dev);
/**
* check whether a device is registered or not
* @param dev - pointer to the device to be checked
*
* @return 0 for success; netative for failure
*/
int u_device_is_registered(struct u_device *dev);
/**
* unregister device from system
* @param dev - pointer to target device to be unregistered
* @return 0 for success; negative for failure
*/
int u_device_unregister(struct u_device *dev);
/**
* delete device from system
*
* @param dev - pointer to device to be deleted
* @return 0 for success; negative for failure
*/
int u_device_del(struct u_device *dev);
/**
* dump device's information, name, id, parent, bus, driver, drv_data included
* @param dev - pointer to target device
* @return 0 for success; netative for failure
*/
int u_device_dump(struct u_device *dev);
int u_device_root_node_init(void);
struct u_dev_node * u_device_node_create(struct u_dev_node *parent, unsigned int dev_id, void *drv_data, char *name);
#if 0
struct u_dev_node * u_device_node_find_by_devid(dev_t devid);
#endif
struct u_dev_node * u_device_node_find_by_pathname(char *pathname);
struct u_dev_node * u_device_node_find_by_dev(struct u_device *u_dev);
struct u_dev_node * u_device_node_find_by_nodename(char *node_name);
int u_device_node_delete(unsigned int dev_id);
#endif //_U_DEVICE_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/char/u_device.h | C | apache-2.0 | 3,881 |
/**
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _U_DRIVER_H_
#define _U_DRIVER_H_
#include <drivers/spinlock.h>
enum U_PM_EVENT {
E_PM_ENTER,
E_PM_L0,
E_PM_L1,
E_PM_EXIT,
};
// TODO: should move this to power manager header file
typedef struct u_pm_ops {
int event;
} u_pm_ops_t;
/**
* struct u_driver_private - driver private information
* should only be accessed by char_core
* @dev_list: device list driven by this driver
* @bus_node: node in bus driver list
*
* */
typedef struct u_driver_private {
spinlock_t lock;
struct dlist_s dev_list;
struct dlist_s bus_node;
struct u_driver *drv;
} u_driver_private_t;
/**
* struct u_bus - bus struct, virtual or hardware bus
*
* @name: driver name
* @next: driver list
* @bus: bus pointer to which the driver belongs
* */
typedef struct u_driver {
char *name;
struct u_bus *bus;
u_driver_private_t *p;
// for legacy drivers
int (*init)(struct u_device *dev);
int (*deinit)(struct u_device *dev);
int (*pm)(struct u_device *dev, u_pm_ops_t state);
// for linux-like drivers
int (*probe)(struct u_device *dev);
int (*remove)(struct u_device *dev);
void (*shutdown)(struct u_device *dev);
int (*suspend)(struct u_device *dev, u_pm_ops_t state);
int (*resume)(struct u_device *dev);
// TODO: when receive IPC ping message call on_ping
int (*on_ping)(struct u_device *dev);
} u_driver_t;
/**
* register a driver into system, init it's private struct before add it into system
*
* @param drv - pointer to target driver to be registered
* @return 0 for success; negative for failure
*/
int u_driver_register(struct u_driver *drv);
/**
* unregister a driver from system
* delete it and then free its private struct
*
* @param drv - pointer to target driver to be registered
* @return 0 for success; negative for failure
*/
int u_driver_unregister(struct u_driver *drv);
/**
* dump driver information
*
* @param drv - pointer to target driver to be dumped
* @return 0 for success; -1 for failure
*
*/
int u_driver_dump(struct u_driver *drv);
#endif //_U_DRIVER_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/char/u_driver.h | C | apache-2.0 | 2,094 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _DDKC_LOG_H_
#define _DDKC_LOG_H_
#include <unistd.h>
#include <sys/types.h>
/*!!!!!!!!!! ONLY loglevel and log format should be modified !!!!!!!!!*/
extern int g_ddkc_log_level;
extern char ddkc_level_tag[];
/*!!!!!!!!!! NEVER TRY to modify the following log defination !!!!!!!!!*/
#define DDKC_LOG_LOUD 0
#define DDKC_LOG_DEBUG 1
#define DDKC_LOG_INFO 2
#define DDKC_LOG_WARN 3
#define DDKC_LOG_ERROR 4
#define ddkc_log(level, format, ...) do { \
if (level >= g_ddkc_log_level) \
printf("<%c><%d> [%s:%d]" format, ddkc_level_tag[level], getpid(), __FUNCTION__, __LINE__, ##__VA_ARGS__); \
} while (0)
#define ddkc_loud(format, ...) ddkc_log(DDKC_LOG_LOUD, format, ##__VA_ARGS__)
#define ddkc_dbg(format, ...) ddkc_log(DDKC_LOG_DEBUG, format, ##__VA_ARGS__)
#define ddkc_info(format, ...) ddkc_log(DDKC_LOG_INFO, format, ##__VA_ARGS__)
#define ddkc_warn(format, ...) ddkc_log(DDKC_LOG_WARN, format, ##__VA_ARGS__)
#define ddkc_err(format, ...) ddkc_log(DDKC_LOG_ERROR, format, ##__VA_ARGS__)
#define ddkc_assert(cond, str, ...) \
do { if (!(cond)) { printf("[ASSERT] %s/" str, __FUNCTION__, __VA_ARGS__); while (1); } } while (0)
#endif //_DDKC_LOG_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/ddkc_log.h | C | apache-2.0 | 1,258 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _DRIVERS_TEST_H_
#define _DRIVERS_TEST_H_
int drivers_test(void);
#endif //_DRIVERS_TEST_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/drivers_test.h | C | apache-2.0 | 167 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _MUTEX_H_
#define _MUTEX_H_
#include <pthread.h>
#include <drivers/bug.h>
#include <drivers/spinlock.h>
#include <drivers/ddkc_log.h>
#include <drivers/spinlock.h>
#define MUTEX_INIT_DONE_FLAG 0xACBDFDBC
/**
* DEFINE_MUTEX(x) will define a mutex,
* but the mutex cannot be initialized when the mutex is global variable
* we use flag to record whether mutex is initialized or not
* */
struct mutex {
unsigned int flag;
spinlock_t s;
pthread_mutex_t m;
};
#define DEFINE_MUTEX(mutexname) struct mutex mutexname = {.flag = 0}
#define __mutex_init(lock, name, key) mutex_init(lock)
#define mutex_lock_nested(lock, depth) mutex_lock(lock)
// TODO: need to re-implement mutex_lock_interruptible
#define mutex_lock_interruptible(lock) ({\
pr_warn("mutex_lock_interruptible is defined as mutex_lock\r\n");\
mutex_lock((lock)); \
0;})
static inline void mutex_init(struct mutex *lock) {
int r = 0;
if (lock->flag == MUTEX_INIT_DONE_FLAG) {
ddkc_warn( "MUTEX:possible mutex reinit detected\r\n");
BUG_ON_MSG(1, "mutex reinit detected");
return;
}
spin_lock_init(&lock->s);
r = pthread_mutex_init(&lock->m, NULL);
if (!r) {
lock->flag = MUTEX_INIT_DONE_FLAG;
ddkc_loud("MUTEX:pthread_mutex_init %p success\r\n", lock);
return;
}
ddkc_err("MUTEX:pthread_mutex_init %p fails, r:%d\r\n", lock, r);
return;
}
static inline void mutex_lock(struct mutex *lock) {
int r = 0;
// TODO: how to guarantee mutex_init procedure is atomic operation?
if (lock->flag != MUTEX_INIT_DONE_FLAG) {
ddkc_loud("MUTEX:uninitialized mutex:%p detected, init it\r\n", lock);
mutex_init(lock);
}
r = pthread_mutex_lock(&lock->m);
if (!r) {
ddkc_loud("MUTEX:pthread_mutex_lock %p success\r\n", lock);
return;
}
ddkc_err("MUTEX:pthread_mutex_lock %p fails, r:%d\r\n", lock, r);
return;
}
static inline int mutex_trylock(struct mutex *lock) {
int r = 0;
if (lock->flag != MUTEX_INIT_DONE_FLAG) {
ddkc_loud("MUTEX:uninitialized mutex:%p detected, init it\r\n", lock);
mutex_init(lock);
}
r = pthread_mutex_trylock(&lock->m);
if (!r) {
ddkc_loud("MUTEX:pthread_mutex_trylock %p success\r\n", lock);
return 1;
}
ddkc_err("MUTEX:pthread_mutex_trylock fails, r:%d\r\n", r);
return 0;
}
static inline void mutex_unlock(struct mutex *lock) {
int r = pthread_mutex_unlock(&lock->m);
if (!r) {
ddkc_loud("MUTEX:pthread_mutex_unlock %p success\r\n", lock);
return;
}
ddkc_err("MUTEX:pthread_mutex_unlock fails, r:%d\r\n", r);
return;
}
static inline void mutex_destroy(struct mutex *lock) {
pthread_mutex_destroy(&lock->m);
lock->flag = ~MUTEX_INIT_DONE_FLAG;
}
#if 0
#define __MUTEX_INITIALIZER(lockname) \
{ \
.blk_obj.blk_list.prev = &blk_obj.blk_list, \
.blk_obj.blk_list.next = &blk_obj.blk_list, \
.blk_obj.blk_policy = BLK_POLICY_PRI, \
.blk_obj.name = name, \
#if (RHINO_CONFIG_TASK_DEL > 0) \
.blk_obj.cancel = 0u, \
#endif \
.mutex_task = NULL, \
.mutex_list = NULL, \
.mm_alloc_flag = K_OBJ_STATIC_ALLOC, \
.blk_obj.obj_type = RHINO_MUTEX_OBJ_TYPE, \
}
#define DEFINE_MUTEX(mutexname) \
struct mutex_s mutexname = __MUTEX_INITIALIZER(mutexname)
#endif
#endif //_MUTEX_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/mutex.h | C | apache-2.0 | 3,376 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef NETDEVICE_H
#define NETDEVICE_H
#include <stdint.h>
#include <stddef.h>
#include <assert.h>
#include "object.h"
#include "device.h"
#include "aos/kernel.h"
#include "aos/vfs.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum net_device_type_e {
NET_DEVICE_TYPE_WIFI,
NET_DEVICE_TYPE_ETH
} net_device_type_t;
typedef enum netbuf_type_e {
NETBUF_TYPE_RAW,
NETBUF_TYPE_PBUF,
NETBUF_TYPE_ATBM,
NETBUF_TYPE_MAX
} netbuf_type_t;
#ifndef ZEROSIZE
#define ZEROSIZE 0
#endif
struct net_device_ops;
typedef struct net_device{
struct net_device_ops* netdev_ops;
void* netif;
net_device_type_t type;
struct platform_device* device;
void* drv_priv;
} net_device_t;
typedef struct net_device_ops{
int (*ndo_init)(net_device_t* ndev);
int (*ndo_deinit)(net_device_t* ndev);
int (*ndo_open)(net_device_t* ndev);
int (*ndo_close)(net_device_t* ndev);
int (*ndo_enable)(net_device_t* ndev);
int (*ndo_disable)(net_device_t* ndev);
int (*ndo_send)(net_device_t* ndev, netbuf_type_t type, void *buf, int len);
int (*ndo_recv)(net_device_t* ndev, netbuf_type_t type, void* buf, int len);
int (*ndo_ioctl)(net_device_t* ndev, struct ifreq *ifr, int cmd);
} net_device_ops_t;
#ifdef __cplusplus
}
#endif
#endif
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/netdevice.h | C | apache-2.0 | 1,346 |
/**
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _U_PLATFORM_BUS_H_
#define _U_PLATFORM_BUS_H_
#include <stdbool.h>
#include "aos/list.h"
#include <drivers/char/u_device.h>
#include <drivers/char/u_driver.h>
#include <drivers/char/u_bus.h>
typedef struct u_platform_device {
const char *name;
int id;
struct u_device dev;
#if 0 //TODO: how to originize hardware resources
unsigned num_resources;
struct u_resource *resource;
#endif
} u_platform_device_t;
typedef struct u_platform_driver {
/* user can select either legacy driver API or linux-like drivers */
/* for legacy drivers */
int (*init)(struct u_platform_device *_dev);
int (*deinit)(struct u_platform_device *_dev);
int (*pm)(struct u_platform_device *dev, u_pm_ops_t state);
/* for linux-like drivers */
int (*probe)(struct u_platform_device *);
int (*remove)(struct u_platform_device *);
void (*shutdown)(struct u_platform_device *);
int (*suspend)(struct u_platform_device *, /*u_pm_ops_t*/int state);
int (*resume)(struct u_platform_device *);
u_driver_t driver;
u_bus_t *bus;
} u_platform_driver_t;
#define to_u_platform_device(x) aos_container_of((x), struct u_platform_device, dev)
#define to_u_platform_driver(x) aos_container_of((x), struct u_platform_driver, driver)
static inline void *u_platform_get_user_data(const struct u_platform_device *pdev)
{
return pdev->dev.user_data;
}
static inline void u_platform_set_user_data(struct u_platform_device *pdev,
void *data)
{
pdev->dev.user_data = data;
}
int u_platform_device_init(void);
u_platform_device_t* u_platform_device_alloc(void);
int u_platform_device_register(u_platform_device_t *dev);
void u_platform_device_del(u_platform_device_t *pdev);
int u_platform_device_unregister(u_platform_device_t *dev);
int u_platform_driver_register(u_platform_driver_t *drv);
int u_platform_driver_unregister(u_platform_driver_t *drv);
#endif //_U_PLATFORM_BUS_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/platform/u_platform_bus.h | C | apache-2.0 | 1,979 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _SPINLOCK_H_
#define _SPINLOCK_H_
#include <stdio.h>
#include <drivers/u_mode.h>
#ifdef CONFIG_PTHREAD_SPINLOCK_SUPPORT
#include <pthread.h>
typedef struct spinlock {
unsigned int flag;
pthread_spinlock_t ps;
} spinlock_t;
#define __SPIN_LOCK_UNLOCKED(lock) { .flag = 0 }
#define DEFINE_SPINLOCK(lock) struct spinlock lock = { \
.flag = 0 \
}
#define spin_lock_init(lock) do { \
int ret = -1; \
if ((lock)->flag == 1) \
break; \
ret = pthread_spin_init(&((lock)->ps), PTHREAD_PROCESS_PRIVATE); \
if (ret) { \
printf("pthread_spin_init failed, ret:%d\r\n", ret); \
} \
(lock)->flag = 1; \
} while (0)
//TODO: how to guarantee this procedure is atomic?
#define spin_lock_irqsave(lock, flags) do { \
(void)flags; \
if (!(lock)->flag) { \
spin_lock_init(lock); \
(lock)->flag = 1; \
} \
pthread_spin_lock(&(lock)->ps); \
} while (0)
#define spin_unlock_irqrestore(lock, flags) do { \
(void)flags; \
pthread_spin_unlock(&(lock)->ps); \
} while (0)
#define spin_lock(lock) do { \
pthread_spin_lock(&((lock)->ps)); \
} while (0)
#define spin_unlock(lock) do { \
pthread_spin_unlock(&((lock)->ps)); \
} while (0)
#define spin_lock_irq(lock) \
unsigned long flags; \
do { \
pthread_spin_lock(&((lock)->ps)); \
} while(0)
#define spin_unlock_irq(lock) do { \
pthread_spin_unlock(&((lock)->ps)); \
} while(0)
#define spin_lock_destroy(lock) do { \
pthread_spin_destroy(&((lock)->ps)); \
} while(0)
#else
#include <aos/kernel.h>
typedef struct spinlock {
unsigned int flag;
aos_spinlock_t as;
} spinlock_t;
#define __SPIN_LOCK_UNLOCKED(lock) { .flag = 0 }
#define DEFINE_SPINLOCK(lock) struct spinlock lock = { \
.flag = 0 \
}
#define spin_lock_init(lock) do { \
aos_spin_lock_init(&((lock)->as)); \
(lock)->flag = 1; \
} while (0)
#define spin_lock_irqsave(lock, flags) do { \
if (!(lock)->flag) { \
aos_spin_lock_init(&((lock)->as)); \
(lock)->flag = 1; \
} \
flags = aos_spin_lock_irqsave(&(lock)->as); \
} while (0)
#define spin_unlock_irqrestore(lock, flags) do { \
(void)flags; \
aos_spin_unlock_irqrestore(&(lock)->as, flags); \
} while (0)
#define spin_lock(lock) do { \
aos_spin_lock(&((lock)->as)); \
} while (0)
#define spin_unlock(lock) do { \
aos_spin_unlock(&((lock)->as)); \
} while (0)
#define spin_lock_irq(lock) \
unsigned long flags; \
do { \
aos_spin_lock(&((lock)->as)); \
} while(0)
#define spin_unlock_irq(lock) do { \
aos_spin_unlock(&((lock)->as)); \
} while(0)
#define spin_lock_destroy(lock) do { \
(lock)->flag = 0; \
} while(0)
#endif
typedef spinlock_t raw_spinlock_t;
#define __RAW_SPIN_LOCK_UNLOCKED(lock) { \
.flag = 0 \
}
#define raw_spin_lock_init(lock) spin_lock_init(lock)
#define raw_spin_lock_irqsave(lock, flags) spin_lock_irqsave(lock, flags)
#define raw_spin_unlock_irqrestore(lock, flags) spin_unlock_irqrestore(lock, flags)
#define raw_spin_lock_irq(lock) spin_lock_irq(lock)
#define raw_spin_unlock_irq(lock) spin_unlock_irq(lock)
#endif //_SPINLOCK_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/spinlock.h | C | apache-2.0 | 3,041 |
/**
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _U_DEVICE_INFO_H_
#define _U_DEVICE_INFO_H_
#include "aos/list.h"
#include <drivers/u_io.h>
struct u_bus_info;
struct u_device_info;
struct u_driver_info;
typedef unsigned int u_dev_t;
typedef struct u_bus_info {
bus_type_e type;
/*TODO: const*/ char *name;
struct dlist_s bus_node;
struct slist_s bus_dev_head;
struct u_driver_info *drv;
} u_bus_info_t;
typedef enum device_state {
DEV_STATE_IDLE = 0x71, /* idle, not bind with any driver */
DEV_STATE_BINDED, /* binded with the driver */
DEV_STATE_SHARED, /* shared state */
DEV_STATE__MAX,
} device_state_e;
/**
* struct u_device_info - the base device struct
* @parent: The device's parent, usually it points to device's bus
* NULL is not allowed for non-bus type device, if the device is not
* attached to any bus, attach to virtual bus named platform
* @dev_name: device's name
* @id: device id
* @dev_res: device resource list
* @devt:
* @state: device state, idle/binded
* @bus: bus of the device
* @drv: driver for this device
* @dev_node: device list
* @bus_dev_node: device list of the same bus
* @drv_dev_node: device list of the same driver
*
* */
typedef struct u_device_info {
struct u_device_info *parent;
/*TODO: const*/ char *dev_name;
unsigned int id;
struct dev_res *res;
u_dev_t devt;
unsigned int state;
struct u_bus_info *bus;
struct u_driver_info *drv;
struct dlist_s dev_node;
struct slist_s bus_dev_node;
struct slist_s drv_dev_node;
} u_device_info_t;
/**
* struct u_driver - device driver information
* @name: driver's name, should be compatible with dev_name (in struct u_device_info)
* of the device it drives
* @path: driver path in file system
* @pid: id of the process in which the driver is loaded, used for IPC
* @tid: id of the thread belongs to the driver, used for IPC
* @drv_dev_node: device list which this driver drives
* @
* */
typedef struct u_driver_info {
/*TODO: const*/ char name[128]; /* TODO: use char* and malloc memory dynamic later */
/*TODO: const*/ char *path; /* driver binary file path */
int type; /* bus, device or subsystem */
int bus_type; /* bus driver's type, platform, sdio, usb and etc. */
unsigned int pid;
unsigned int tid;
struct slist_s drv_dev_head;
struct dlist_s drv_node;
} u_driver_info_t;
typedef enum drv_type {
DRV_TYPE_MIN,
DRV_TYPE_BUS,
DRV_TYPE_SUBSYS,
DRV_TYPE_CHAR_DEV,
DRV_TYPE_BLOCK_DEV,
DRV_TYPE_NET_DEV,
DRV_TYPE_MAX
} drv_type_e;
typedef struct u_driver_bin_info {
int type; /* bus, device or subsystem */
int bus_type; /* bus_type_e */
char *name; /* driver name got from binary */
} u_driver_bin_info_t;
#endif //_U_DEVICE_INFO_H_
| YifuLiu/AliOS-Things | components/drivers/core/base/include/drivers/u_device_info.h | C | apache-2.0 | 2,812 |