id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
15,260
session.h
Studio3T_robomongo/src/third-party/libssh2-1.9.0/sources/src/session.h
#ifndef LIBSSH2_SESSION_H #define LIBSSH2_SESSION_H /* Copyright (c) 2004-2007 Sara Golemon <sarag@libssh2.org> * Copyright (c) 2009-2010 by Daniel Stenberg * Copyright (c) 2010 Simon Josefsson <simon@josefsson.org> * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ /* Conveniance-macros to allow code like this; int rc = BLOCK_ADJUST(rc, session, session_startup(session, sock) ); int rc = BLOCK_ADJUST_ERRNO(ptr, session, session_startup(session, sock) ); The point of course being to make sure that while in non-blocking mode these always return no matter what the return code is, but in blocking mode it blocks if EAGAIN is the reason for the return from the underlying function. */ #define BLOCK_ADJUST(rc, sess, x) \ do { \ time_t entry_time = time(NULL); \ do { \ rc = x; \ /* the order of the check below is important to properly deal with \ the case when the 'sess' is freed */ \ if((rc != LIBSSH2_ERROR_EAGAIN) || !sess->api_block_mode) \ break; \ rc = _libssh2_wait_socket(sess, entry_time); \ } while(!rc); \ } while(0) /* * For functions that returns a pointer, we need to check if the API is * non-blocking and return immediately. If the pointer is non-NULL we return * immediately. If the API is blocking and we get a NULL we check the errno * and *only* if that is EAGAIN we loop and wait for socket action. */ #define BLOCK_ADJUST_ERRNO(ptr, sess, x) \ do { \ time_t entry_time = time(NULL); \ int rc; \ do { \ ptr = x; \ if(!sess->api_block_mode || \ (ptr != NULL) || \ (libssh2_session_last_errno(sess) != LIBSSH2_ERROR_EAGAIN) ) \ break; \ rc = _libssh2_wait_socket(sess, entry_time); \ } while(!rc); \ } while(0) int _libssh2_wait_socket(LIBSSH2_SESSION *session, time_t entry_time); /* this is the lib-internal set blocking function */ int _libssh2_session_set_blocking(LIBSSH2_SESSION * session, int blocking); #endif /* LIBSSH2_SESSION_H */
3,631
C++
.h
83
39.385542
78
0.699265
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,261
transport.h
Studio3T_robomongo/src/third-party/libssh2-1.9.0/sources/src/transport.h
#ifndef __LIBSSH2_TRANSPORT_H #define __LIBSSH2_TRANSPORT_H /* Copyright (C) 2007 The Written Word, Inc. All rights reserved. * Copyright (C) 2009-2010 by Daniel Stenberg * Author: Daniel Stenberg <daniel@haxx.se> * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file handles reading and writing to the SECSH transport layer. RFC4253. */ #include "libssh2_priv.h" #include "packet.h" /* * libssh2_transport_send * * Send a packet, encrypting it and adding a MAC code if necessary * Returns 0 on success, non-zero on failure. * * The data is provided as _two_ data areas that are combined by this * function. The 'data' part is sent immediately before 'data2'. 'data2' can * be set to NULL (or data2_len to 0) to only use a single part. * * Returns LIBSSH2_ERROR_EAGAIN if it would block or if the whole packet was * not sent yet. If it does so, the caller should call this function again as * soon as it is likely that more data can be sent, and this function MUST * then be called with the same argument set (same data pointer and same * data_len) until ERROR_NONE or failure is returned. * * This function DOES NOT call _libssh2_error() on any errors. */ int _libssh2_transport_send(LIBSSH2_SESSION *session, const unsigned char *data, size_t data_len, const unsigned char *data2, size_t data2_len); /* * _libssh2_transport_read * * Collect a packet into the input brigade block only controls whether or not * to wait for a packet to start. * * Returns packet type added to input brigade (PACKET_NONE if nothing added), * or PACKET_FAIL on failure and PACKET_EAGAIN if it couldn't process a full * packet. */ /* * This function reads the binary stream as specified in chapter 6 of RFC4253 * "The Secure Shell (SSH) Transport Layer Protocol" */ int _libssh2_transport_read(LIBSSH2_SESSION * session); #endif /* __LIBSSH2_TRANSPORT_H */
3,437
C++
.h
80
40.3375
79
0.748358
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,262
comp.h
Studio3T_robomongo/src/third-party/libssh2-1.9.0/sources/src/comp.h
#ifndef __LIBSSH2_COMP_H #define __LIBSSH2_COMP_H /* Copyright (C) 2009-2010 by Daniel Stenberg * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * */ #include "libssh2_priv.h" const LIBSSH2_COMP_METHOD **_libssh2_comp_methods(LIBSSH2_SESSION *session); #endif /* __LIBSSH2_COMP_H */
1,781
C++
.h
41
41.487805
76
0.770737
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,263
mac.h
Studio3T_robomongo/src/third-party/libssh2-1.9.0/sources/src/mac.h
#ifndef __LIBSSH2_MAC_H #define __LIBSSH2_MAC_H /* Copyright (C) 2009-2010 by Daniel Stenberg * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * */ #include "libssh2_priv.h" struct _LIBSSH2_MAC_METHOD { const char *name; /* The length of a given MAC packet */ int mac_len; /* integrity key length */ int key_len; /* Message Authentication Code Hashing algo */ int (*init) (LIBSSH2_SESSION * session, unsigned char *key, int *free_key, void **abstract); int (*hash) (LIBSSH2_SESSION * session, unsigned char *buf, uint32_t seqno, const unsigned char *packet, uint32_t packet_len, const unsigned char *addtl, uint32_t addtl_len, void **abstract); int (*dtor) (LIBSSH2_SESSION * session, void **abstract); }; typedef struct _LIBSSH2_MAC_METHOD LIBSSH2_MAC_METHOD; const LIBSSH2_MAC_METHOD **_libssh2_mac_methods(void); #endif /* __LIBSSH2_MAC_H */
2,452
C++
.h
58
38.724138
78
0.730398
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,264
libgcrypt.h
Studio3T_robomongo/src/third-party/libssh2-1.9.0/sources/src/libgcrypt.h
/* * Copyright (C) 2008, 2009, 2010 Simon Josefsson * Copyright (C) 2006, 2007, The Written Word, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #include <gcrypt.h> #define LIBSSH2_MD5 1 #define LIBSSH2_HMAC_RIPEMD 1 #define LIBSSH2_HMAC_SHA256 1 #define LIBSSH2_HMAC_SHA512 1 #define LIBSSH2_AES 1 #define LIBSSH2_AES_CTR 1 #define LIBSSH2_BLOWFISH 1 #define LIBSSH2_RC4 1 #define LIBSSH2_CAST 1 #define LIBSSH2_3DES 1 #define LIBSSH2_RSA 1 #define LIBSSH2_DSA 1 #define LIBSSH2_ECDSA 0 #define LIBSSH2_ED25519 0 #define MD5_DIGEST_LENGTH 16 #define SHA_DIGEST_LENGTH 20 #define SHA256_DIGEST_LENGTH 32 #define SHA384_DIGEST_LENGTH 48 #define SHA512_DIGEST_LENGTH 64 #define EC_MAX_POINT_LEN ((528 * 2 / 8) + 1) #define _libssh2_random(buf, len) \ (gcry_randomize ((buf), (len), GCRY_STRONG_RANDOM), 1) #define libssh2_prepare_iovec(vec, len) /* Empty. */ #define libssh2_sha1_ctx gcry_md_hd_t /* returns 0 in case of failure */ #define libssh2_sha1_init(ctx) \ (GPG_ERR_NO_ERROR == gcry_md_open(ctx, GCRY_MD_SHA1, 0)) #define libssh2_sha1_update(ctx, data, len) \ gcry_md_write(ctx, (unsigned char *) data, len) #define libssh2_sha1_final(ctx, out) \ memcpy(out, gcry_md_read(ctx, 0), SHA_DIGEST_LENGTH), gcry_md_close(ctx) #define libssh2_sha1(message, len, out) \ gcry_md_hash_buffer(GCRY_MD_SHA1, out, message, len) #define libssh2_sha256_ctx gcry_md_hd_t #define libssh2_sha256_init(ctx) \ (GPG_ERR_NO_ERROR == gcry_md_open(ctx, GCRY_MD_SHA256, 0)) #define libssh2_sha256_update(ctx, data, len) \ gcry_md_write(ctx, (unsigned char *) data, len) #define libssh2_sha256_final(ctx, out) \ memcpy(out, gcry_md_read(ctx, 0), SHA256_DIGEST_LENGTH), gcry_md_close(ctx) #define libssh2_sha256(message, len, out) \ gcry_md_hash_buffer(GCRY_MD_SHA256, out, message, len) #define libssh2_sha384_ctx gcry_md_hd_t #define libssh2_sha384_init(ctx) \ (GPG_ERR_NO_ERROR == gcry_md_open(ctx, GCRY_MD_SHA384, 0)) #define libssh2_sha384_update(ctx, data, len) \ gcry_md_write(ctx, (unsigned char *) data, len) #define libssh2_sha384_final(ctx, out) \ memcpy(out, gcry_md_read(ctx, 0), SHA384_DIGEST_LENGTH), gcry_md_close(ctx) #define libssh2_sha384(message, len, out) \ gcry_md_hash_buffer(GCRY_MD_SHA384, out, message, len) #define libssh2_sha512_ctx gcry_md_hd_t #define libssh2_sha512_init(ctx) \ (GPG_ERR_NO_ERROR == gcry_md_open(ctx, GCRY_MD_SHA512, 0)) #define libssh2_sha512_update(ctx, data, len) \ gcry_md_write(ctx, (unsigned char *) data, len) #define libssh2_sha512_final(ctx, out) \ memcpy(out, gcry_md_read(ctx, 0), SHA512_DIGEST_LENGTH), gcry_md_close(ctx) #define libssh2_sha512(message, len, out) \ gcry_md_hash_buffer(GCRY_MD_SHA512, out, message, len) #define libssh2_md5_ctx gcry_md_hd_t /* returns 0 in case of failure */ #define libssh2_md5_init(ctx) \ (GPG_ERR_NO_ERROR == gcry_md_open(ctx, GCRY_MD_MD5, 0)) #define libssh2_md5_update(ctx, data, len) \ gcry_md_write(ctx, (unsigned char *) data, len) #define libssh2_md5_final(ctx, out) \ memcpy(out, gcry_md_read(ctx, 0), MD5_DIGEST_LENGTH), gcry_md_close(ctx) #define libssh2_md5(message, len, out) \ gcry_md_hash_buffer(GCRY_MD_MD5, out, message, len) #define libssh2_hmac_ctx gcry_md_hd_t #define libssh2_hmac_ctx_init(ctx) #define libssh2_hmac_sha1_init(ctx, key, keylen) \ gcry_md_open(ctx, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC), \ gcry_md_setkey(*ctx, key, keylen) #define libssh2_hmac_md5_init(ctx, key, keylen) \ gcry_md_open(ctx, GCRY_MD_MD5, GCRY_MD_FLAG_HMAC), \ gcry_md_setkey(*ctx, key, keylen) #define libssh2_hmac_ripemd160_init(ctx, key, keylen) \ gcry_md_open(ctx, GCRY_MD_RMD160, GCRY_MD_FLAG_HMAC), \ gcry_md_setkey(*ctx, key, keylen) #define libssh2_hmac_sha256_init(ctx, key, keylen) \ gcry_md_open(ctx, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC), \ gcry_md_setkey(*ctx, key, keylen) #define libssh2_hmac_sha512_init(ctx, key, keylen) \ gcry_md_open(ctx, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC), \ gcry_md_setkey(*ctx, key, keylen) #define libssh2_hmac_update(ctx, data, datalen) \ gcry_md_write(ctx, (unsigned char *) data, datalen) #define libssh2_hmac_final(ctx, data) \ memcpy(data, gcry_md_read(ctx, 0), \ gcry_md_get_algo_dlen(gcry_md_get_algo(ctx))) #define libssh2_hmac_cleanup(ctx) gcry_md_close (*ctx); #define libssh2_crypto_init() gcry_control (GCRYCTL_DISABLE_SECMEM) #define libssh2_crypto_exit() #define libssh2_rsa_ctx struct gcry_sexp #define _libssh2_rsa_free(rsactx) gcry_sexp_release (rsactx) #define libssh2_dsa_ctx struct gcry_sexp #define _libssh2_dsa_free(dsactx) gcry_sexp_release (dsactx) #if LIBSSH2_ECDSA #else #define _libssh2_ec_key void #endif #define _libssh2_cipher_type(name) int name #define _libssh2_cipher_ctx gcry_cipher_hd_t #define _libssh2_gcry_ciphermode(c,m) ((c << 8) | m) #define _libssh2_gcry_cipher(c) (c >> 8) #define _libssh2_gcry_mode(m) (m & 0xFF) #define _libssh2_cipher_aes256ctr \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CTR) #define _libssh2_cipher_aes192ctr \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CTR) #define _libssh2_cipher_aes128ctr \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CTR) #define _libssh2_cipher_aes256 \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_aes192 \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_aes128 \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_blowfish \ _libssh2_gcry_ciphermode(GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_arcfour \ _libssh2_gcry_ciphermode(GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM) #define _libssh2_cipher_cast5 \ _libssh2_gcry_ciphermode(GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_3des \ _libssh2_gcry_ciphermode(GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_dtor(ctx) gcry_cipher_close(*(ctx)) #define _libssh2_bn struct gcry_mpi #define _libssh2_bn_ctx int #define _libssh2_bn_ctx_new() 0 #define _libssh2_bn_ctx_free(bnctx) ((void)0) #define _libssh2_bn_init() gcry_mpi_new(0) #define _libssh2_bn_init_from_bin() NULL /* because gcry_mpi_scan() creates a new bignum */ #define _libssh2_bn_set_word(bn, val) gcry_mpi_set_ui(bn, val) #define _libssh2_bn_from_bin(bn, len, val) \ gcry_mpi_scan(&((bn)), GCRYMPI_FMT_USG, val, len, NULL) #define _libssh2_bn_to_bin(bn, val) \ gcry_mpi_print(GCRYMPI_FMT_USG, val, _libssh2_bn_bytes(bn), NULL, bn) #define _libssh2_bn_bytes(bn) \ (gcry_mpi_get_nbits (bn) / 8 + \ ((gcry_mpi_get_nbits (bn) % 8 == 0) ? 0 : 1)) #define _libssh2_bn_bits(bn) gcry_mpi_get_nbits (bn) #define _libssh2_bn_free(bn) gcry_mpi_release(bn) #define _libssh2_dh_ctx struct gcry_mpi * #define libssh2_dh_init(dhctx) _libssh2_dh_init(dhctx) #define libssh2_dh_key_pair(dhctx, public, g, p, group_order, bnctx) \ _libssh2_dh_key_pair(dhctx, public, g, p, group_order) #define libssh2_dh_secret(dhctx, secret, f, p, bnctx) \ _libssh2_dh_secret(dhctx, secret, f, p) #define libssh2_dh_dtor(dhctx) _libssh2_dh_dtor(dhctx) extern void _libssh2_dh_init(_libssh2_dh_ctx *dhctx); extern int _libssh2_dh_key_pair(_libssh2_dh_ctx *dhctx, _libssh2_bn *public, _libssh2_bn *g, _libssh2_bn *p, int group_order); extern int _libssh2_dh_secret(_libssh2_dh_ctx *dhctx, _libssh2_bn *secret, _libssh2_bn *f, _libssh2_bn *p); extern void _libssh2_dh_dtor(_libssh2_dh_ctx *dhctx);
9,312
C++
.h
199
44.060302
77
0.714585
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,265
openssl.h
Studio3T_robomongo/src/third-party/libssh2-1.9.0/sources/src/openssl.h
/* Copyright (C) 2009, 2010 Simon Josefsson * Copyright (C) 2006, 2007 The Written Word, Inc. All rights reserved. * * Author: Simon Josefsson * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #include <openssl/opensslconf.h> #include <openssl/sha.h> #include <openssl/rsa.h> #ifndef OPENSSL_NO_ENGINE #include <openssl/engine.h> #endif #ifndef OPENSSL_NO_DSA #include <openssl/dsa.h> #endif #ifndef OPENSSL_NO_MD5 #include <openssl/md5.h> #endif #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/bn.h> #include <openssl/pem.h> #include <openssl/rand.h> #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ !defined(LIBRESSL_VERSION_NUMBER) # define HAVE_OPAQUE_STRUCTS 1 #endif #ifdef OPENSSL_NO_RSA # define LIBSSH2_RSA 0 #else # define LIBSSH2_RSA 1 #endif #ifdef OPENSSL_NO_DSA # define LIBSSH2_DSA 0 #else # define LIBSSH2_DSA 1 #endif #ifdef OPENSSL_NO_ECDSA # define LIBSSH2_ECDSA 0 #else # define LIBSSH2_ECDSA 1 #endif #if OPENSSL_VERSION_NUMBER >= 0x10101000L && \ !defined(LIBRESSL_VERSION_NUMBER) # define LIBSSH2_ED25519 1 #else # define LIBSSH2_ED25519 0 #endif #ifdef OPENSSL_NO_MD5 # define LIBSSH2_MD5 0 #else # define LIBSSH2_MD5 1 #endif #ifdef OPENSSL_NO_RIPEMD # define LIBSSH2_HMAC_RIPEMD 0 #else # define LIBSSH2_HMAC_RIPEMD 1 #endif #define LIBSSH2_HMAC_SHA256 1 #define LIBSSH2_HMAC_SHA512 1 #if OPENSSL_VERSION_NUMBER >= 0x00907000L && !defined(OPENSSL_NO_AES) # define LIBSSH2_AES_CTR 1 # define LIBSSH2_AES 1 #else # define LIBSSH2_AES_CTR 0 # define LIBSSH2_AES 0 #endif #ifdef OPENSSL_NO_BF # define LIBSSH2_BLOWFISH 0 #else # define LIBSSH2_BLOWFISH 1 #endif #ifdef OPENSSL_NO_RC4 # define LIBSSH2_RC4 0 #else # define LIBSSH2_RC4 1 #endif #ifdef OPENSSL_NO_CAST # define LIBSSH2_CAST 0 #else # define LIBSSH2_CAST 1 #endif #ifdef OPENSSL_NO_DES # define LIBSSH2_3DES 0 #else # define LIBSSH2_3DES 1 #endif #define EC_MAX_POINT_LEN ((528 * 2 / 8) + 1) #define _libssh2_random(buf, len) RAND_bytes ((buf), (len)) #define libssh2_prepare_iovec(vec, len) /* Empty. */ #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha1_ctx EVP_MD_CTX * #else #define libssh2_sha1_ctx EVP_MD_CTX #endif /* returns 0 in case of failure */ int _libssh2_sha1_init(libssh2_sha1_ctx *ctx); #define libssh2_sha1_init(x) _libssh2_sha1_init(x) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha1_update(ctx, data, len) EVP_DigestUpdate(ctx, data, len) #define libssh2_sha1_final(ctx, out) do { \ EVP_DigestFinal(ctx, out, NULL); \ EVP_MD_CTX_free(ctx); \ } while(0) #else #define libssh2_sha1_update(ctx, data, len) EVP_DigestUpdate(&(ctx), data, len) #define libssh2_sha1_final(ctx, out) EVP_DigestFinal(&(ctx), out, NULL) #endif int _libssh2_sha1(const unsigned char *message, unsigned long len, unsigned char *out); #define libssh2_sha1(x,y,z) _libssh2_sha1(x,y,z) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha256_ctx EVP_MD_CTX * #else #define libssh2_sha256_ctx EVP_MD_CTX #endif /* returns 0 in case of failure */ int _libssh2_sha256_init(libssh2_sha256_ctx *ctx); #define libssh2_sha256_init(x) _libssh2_sha256_init(x) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha256_update(ctx, data, len) EVP_DigestUpdate(ctx, data, len) #define libssh2_sha256_final(ctx, out) do { \ EVP_DigestFinal(ctx, out, NULL); \ EVP_MD_CTX_free(ctx); \ } while(0) #else #define libssh2_sha256_update(ctx, data, len) \ EVP_DigestUpdate(&(ctx), data, len) #define libssh2_sha256_final(ctx, out) EVP_DigestFinal(&(ctx), out, NULL) #endif int _libssh2_sha256(const unsigned char *message, unsigned long len, unsigned char *out); #define libssh2_sha256(x,y,z) _libssh2_sha256(x,y,z) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha384_ctx EVP_MD_CTX * #else #define libssh2_sha384_ctx EVP_MD_CTX #endif /* returns 0 in case of failure */ int _libssh2_sha384_init(libssh2_sha384_ctx *ctx); #define libssh2_sha384_init(x) _libssh2_sha384_init(x) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha384_update(ctx, data, len) EVP_DigestUpdate(ctx, data, len) #define libssh2_sha384_final(ctx, out) do { \ EVP_DigestFinal(ctx, out, NULL); \ EVP_MD_CTX_free(ctx); \ } while(0) #else #define libssh2_sha384_update(ctx, data, len) \ EVP_DigestUpdate(&(ctx), data, len) #define libssh2_sha384_final(ctx, out) EVP_DigestFinal(&(ctx), out, NULL) #endif int _libssh2_sha384(const unsigned char *message, unsigned long len, unsigned char *out); #define libssh2_sha384(x,y,z) _libssh2_sha384(x,y,z) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha512_ctx EVP_MD_CTX * #else #define libssh2_sha512_ctx EVP_MD_CTX #endif /* returns 0 in case of failure */ int _libssh2_sha512_init(libssh2_sha512_ctx *ctx); #define libssh2_sha512_init(x) _libssh2_sha512_init(x) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha512_update(ctx, data, len) EVP_DigestUpdate(ctx, data, len) #define libssh2_sha512_final(ctx, out) do { \ EVP_DigestFinal(ctx, out, NULL); \ EVP_MD_CTX_free(ctx); \ } while(0) #else #define libssh2_sha512_update(ctx, data, len) \ EVP_DigestUpdate(&(ctx), data, len) #define libssh2_sha512_final(ctx, out) EVP_DigestFinal(&(ctx), out, NULL) #endif int _libssh2_sha512(const unsigned char *message, unsigned long len, unsigned char *out); #define libssh2_sha512(x,y,z) _libssh2_sha512(x,y,z) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_md5_ctx EVP_MD_CTX * #else #define libssh2_md5_ctx EVP_MD_CTX #endif /* returns 0 in case of failure */ int _libssh2_md5_init(libssh2_md5_ctx *ctx); #define libssh2_md5_init(x) _libssh2_md5_init(x) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_md5_update(ctx, data, len) EVP_DigestUpdate(ctx, data, len) #define libssh2_md5_final(ctx, out) do { \ EVP_DigestFinal(ctx, out, NULL); \ EVP_MD_CTX_free(ctx); \ } while(0) #else #define libssh2_md5_update(ctx, data, len) EVP_DigestUpdate(&(ctx), data, len) #define libssh2_md5_final(ctx, out) EVP_DigestFinal(&(ctx), out, NULL) #endif #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_hmac_ctx HMAC_CTX * #define libssh2_hmac_ctx_init(ctx) ctx = HMAC_CTX_new() #define libssh2_hmac_sha1_init(ctx, key, keylen) \ HMAC_Init_ex(*(ctx), key, keylen, EVP_sha1(), NULL) #define libssh2_hmac_md5_init(ctx, key, keylen) \ HMAC_Init_ex(*(ctx), key, keylen, EVP_md5(), NULL) #define libssh2_hmac_ripemd160_init(ctx, key, keylen) \ HMAC_Init_ex(*(ctx), key, keylen, EVP_ripemd160(), NULL) #define libssh2_hmac_sha256_init(ctx, key, keylen) \ HMAC_Init_ex(*(ctx), key, keylen, EVP_sha256(), NULL) #define libssh2_hmac_sha512_init(ctx, key, keylen) \ HMAC_Init_ex(*(ctx), key, keylen, EVP_sha512(), NULL) #define libssh2_hmac_update(ctx, data, datalen) \ HMAC_Update(ctx, data, datalen) #define libssh2_hmac_final(ctx, data) HMAC_Final(ctx, data, NULL) #define libssh2_hmac_cleanup(ctx) HMAC_CTX_free(*(ctx)) #else #define libssh2_hmac_ctx HMAC_CTX #define libssh2_hmac_ctx_init(ctx) \ HMAC_CTX_init(&ctx) #define libssh2_hmac_sha1_init(ctx, key, keylen) \ HMAC_Init_ex(ctx, key, keylen, EVP_sha1(), NULL) #define libssh2_hmac_md5_init(ctx, key, keylen) \ HMAC_Init_ex(ctx, key, keylen, EVP_md5(), NULL) #define libssh2_hmac_ripemd160_init(ctx, key, keylen) \ HMAC_Init_ex(ctx, key, keylen, EVP_ripemd160(), NULL) #define libssh2_hmac_sha256_init(ctx, key, keylen) \ HMAC_Init_ex(ctx, key, keylen, EVP_sha256(), NULL) #define libssh2_hmac_sha512_init(ctx, key, keylen) \ HMAC_Init_ex(ctx, key, keylen, EVP_sha512(), NULL) #define libssh2_hmac_update(ctx, data, datalen) \ HMAC_Update(&(ctx), data, datalen) #define libssh2_hmac_final(ctx, data) HMAC_Final(&(ctx), data, NULL) #define libssh2_hmac_cleanup(ctx) HMAC_cleanup(ctx) #endif extern void _libssh2_openssl_crypto_init(void); extern void _libssh2_openssl_crypto_exit(void); #define libssh2_crypto_init() _libssh2_openssl_crypto_init() #define libssh2_crypto_exit() _libssh2_openssl_crypto_exit() #define libssh2_rsa_ctx RSA #define _libssh2_rsa_free(rsactx) RSA_free(rsactx) #define libssh2_dsa_ctx DSA #define _libssh2_dsa_free(dsactx) DSA_free(dsactx) #ifdef LIBSSH2_ECDSA #define libssh2_ecdsa_ctx EC_KEY #define _libssh2_ecdsa_free(ecdsactx) EC_KEY_free(ecdsactx) #define _libssh2_ec_key EC_KEY typedef enum { LIBSSH2_EC_CURVE_NISTP256 = NID_X9_62_prime256v1, LIBSSH2_EC_CURVE_NISTP384 = NID_secp384r1, LIBSSH2_EC_CURVE_NISTP521 = NID_secp521r1 } libssh2_curve_type; #else #define _libssh2_ec_key void #endif /* LIBSSH2_ECDSA */ #ifdef LIBSSH2_ED25519 typedef struct { EVP_PKEY *public_key; EVP_PKEY *private_key; } libssh2_curve25519_keys; #define libssh2_ed25519_ctx libssh2_curve25519_keys #define libssh2_x25519_ctx libssh2_curve25519_keys #define _libssh2_ed25519_new_ctx() calloc(1, sizeof(libssh2_ed25519_ctx)) #define _libssh2_ed25519_free(ctx) do { \ if(ctx) { \ if(ctx->public_key) EVP_PKEY_free(ctx->public_key); \ if(ctx->private_key) EVP_PKEY_free(ctx->private_key); \ free(ctx); \ } \ } while(0) #define _libssh2_x25519_free(ctx) _libssh2_ed25519_free(ctx) #endif /* ED25519 */ #define _libssh2_cipher_type(name) const EVP_CIPHER *(*name)(void) #ifdef HAVE_OPAQUE_STRUCTS #define _libssh2_cipher_ctx EVP_CIPHER_CTX * #else #define _libssh2_cipher_ctx EVP_CIPHER_CTX #endif #define _libssh2_cipher_aes256 EVP_aes_256_cbc #define _libssh2_cipher_aes192 EVP_aes_192_cbc #define _libssh2_cipher_aes128 EVP_aes_128_cbc #ifdef HAVE_EVP_AES_128_CTR #define _libssh2_cipher_aes128ctr EVP_aes_128_ctr #define _libssh2_cipher_aes192ctr EVP_aes_192_ctr #define _libssh2_cipher_aes256ctr EVP_aes_256_ctr #else #define _libssh2_cipher_aes128ctr _libssh2_EVP_aes_128_ctr #define _libssh2_cipher_aes192ctr _libssh2_EVP_aes_192_ctr #define _libssh2_cipher_aes256ctr _libssh2_EVP_aes_256_ctr #endif #define _libssh2_cipher_blowfish EVP_bf_cbc #define _libssh2_cipher_arcfour EVP_rc4 #define _libssh2_cipher_cast5 EVP_cast5_cbc #define _libssh2_cipher_3des EVP_des_ede3_cbc #ifdef HAVE_OPAQUE_STRUCTS #define _libssh2_cipher_dtor(ctx) EVP_CIPHER_CTX_free(*(ctx)) #else #define _libssh2_cipher_dtor(ctx) EVP_CIPHER_CTX_cleanup(ctx) #endif #define _libssh2_bn BIGNUM #define _libssh2_bn_ctx BN_CTX #define _libssh2_bn_ctx_new() BN_CTX_new() #define _libssh2_bn_ctx_free(bnctx) BN_CTX_free(bnctx) #define _libssh2_bn_init() BN_new() #define _libssh2_bn_init_from_bin() _libssh2_bn_init() #define _libssh2_bn_set_word(bn, val) BN_set_word(bn, val) #define _libssh2_bn_from_bin(bn, len, val) BN_bin2bn(val, len, bn) #define _libssh2_bn_to_bin(bn, val) BN_bn2bin(bn, val) #define _libssh2_bn_bytes(bn) BN_num_bytes(bn) #define _libssh2_bn_bits(bn) BN_num_bits(bn) #define _libssh2_bn_free(bn) BN_clear_free(bn) #define _libssh2_dh_ctx BIGNUM * #define libssh2_dh_init(dhctx) _libssh2_dh_init(dhctx) #define libssh2_dh_key_pair(dhctx, public, g, p, group_order, bnctx) \ _libssh2_dh_key_pair(dhctx, public, g, p, group_order, bnctx) #define libssh2_dh_secret(dhctx, secret, f, p, bnctx) \ _libssh2_dh_secret(dhctx, secret, f, p, bnctx) #define libssh2_dh_dtor(dhctx) _libssh2_dh_dtor(dhctx) extern void _libssh2_dh_init(_libssh2_dh_ctx *dhctx); extern int _libssh2_dh_key_pair(_libssh2_dh_ctx *dhctx, _libssh2_bn *public, _libssh2_bn *g, _libssh2_bn *p, int group_order, _libssh2_bn_ctx *bnctx); extern int _libssh2_dh_secret(_libssh2_dh_ctx *dhctx, _libssh2_bn *secret, _libssh2_bn *f, _libssh2_bn *p, _libssh2_bn_ctx *bnctx); extern void _libssh2_dh_dtor(_libssh2_dh_ctx *dhctx); const EVP_CIPHER *_libssh2_EVP_aes_128_ctr(void); const EVP_CIPHER *_libssh2_EVP_aes_192_ctr(void); const EVP_CIPHER *_libssh2_EVP_aes_256_ctr(void);
13,794
C++
.h
359
34.584958
79
0.706238
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,266
libssh2.h
Studio3T_robomongo/src/third-party/libssh2-1.7.0/sources/include/libssh2.h
/* Copyright (c) 2004-2009, Sara Golemon <sarag@libssh2.org> * Copyright (c) 2009-2015 Daniel Stenberg * Copyright (c) 2010 Simon Josefsson <simon@josefsson.org> * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifndef LIBSSH2_H #define LIBSSH2_H 1 #define LIBSSH2_COPYRIGHT "2004-2016 The libssh2 project and its contributors." /* We use underscore instead of dash when appending DEV in dev versions just to make the BANNER define (used by src/session.c) be a valid SSH banner. Release versions have no appended strings and may of course not have dashes either. */ #define LIBSSH2_VERSION "1.7.0_DEV" /* The numeric version number is also available "in parts" by using these defines: */ #define LIBSSH2_VERSION_MAJOR 1 #define LIBSSH2_VERSION_MINOR 7 #define LIBSSH2_VERSION_PATCH 0 /* This is the numeric version of the libssh2 version number, meant for easier parsing and comparions by programs. The LIBSSH2_VERSION_NUM define will always follow this syntax: 0xXXYYZZ Where XX, YY and ZZ are the main version, release and patch numbers in hexadecimal (using 8 bits each). All three numbers are always represented using two digits. 1.2 would appear as "0x010200" while version 9.11.7 appears as "0x090b07". This 6-digit (24 bits) hexadecimal number does not show pre-release number, and it is always a greater number in a more recent release. It makes comparisons with greater than and less than work. */ #define LIBSSH2_VERSION_NUM 0x010700 /* * This is the date and time when the full source package was created. The * timestamp is not stored in the source code repo, as the timestamp is * properly set in the tarballs by the maketgz script. * * The format of the date should follow this template: * * "Mon Feb 12 11:35:33 UTC 2007" */ #define LIBSSH2_TIMESTAMP "DEV" #ifndef RC_INVOKED #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32 # include <basetsd.h> # include <winsock2.h> #endif #include <stddef.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> /* Allow alternate API prefix from CFLAGS or calling app */ #ifndef LIBSSH2_API # ifdef LIBSSH2_WIN32 # ifdef _WINDLL # ifdef LIBSSH2_LIBRARY # define LIBSSH2_API __declspec(dllexport) # else # define LIBSSH2_API __declspec(dllimport) # endif /* LIBSSH2_LIBRARY */ # else # define LIBSSH2_API # endif # else /* !LIBSSH2_WIN32 */ # define LIBSSH2_API # endif /* LIBSSH2_WIN32 */ #endif /* LIBSSH2_API */ #ifdef HAVE_SYS_UIO_H # include <sys/uio.h> #endif #if (defined(NETWARE) && !defined(__NOVELL_LIBC__)) # include <sys/bsdskt.h> typedef unsigned char uint8_t; typedef unsigned int uint32_t; #endif #ifdef _MSC_VER typedef unsigned char uint8_t; typedef unsigned int uint32_t; typedef unsigned __int64 libssh2_uint64_t; typedef __int64 libssh2_int64_t; #ifndef ssize_t typedef SSIZE_T ssize_t; #endif #else typedef unsigned long long libssh2_uint64_t; typedef long long libssh2_int64_t; #endif #ifdef WIN32 typedef SOCKET libssh2_socket_t; #define LIBSSH2_INVALID_SOCKET INVALID_SOCKET #else /* !WIN32 */ typedef int libssh2_socket_t; #define LIBSSH2_INVALID_SOCKET -1 #endif /* WIN32 */ /* * Determine whether there is small or large file support on windows. */ #if defined(_MSC_VER) && !defined(_WIN32_WCE) # if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) # define LIBSSH2_USE_WIN32_LARGE_FILES # else # define LIBSSH2_USE_WIN32_SMALL_FILES # endif #endif #if defined(__MINGW32__) && !defined(LIBSSH2_USE_WIN32_LARGE_FILES) # define LIBSSH2_USE_WIN32_LARGE_FILES #endif #if defined(__WATCOMC__) && !defined(LIBSSH2_USE_WIN32_LARGE_FILES) # define LIBSSH2_USE_WIN32_LARGE_FILES #endif #if defined(__POCC__) # undef LIBSSH2_USE_WIN32_LARGE_FILES #endif #if defined(_WIN32) && !defined(LIBSSH2_USE_WIN32_LARGE_FILES) && \ !defined(LIBSSH2_USE_WIN32_SMALL_FILES) # define LIBSSH2_USE_WIN32_SMALL_FILES #endif /* * Large file (>2Gb) support using WIN32 functions. */ #ifdef LIBSSH2_USE_WIN32_LARGE_FILES # include <io.h> # include <sys/types.h> # include <sys/stat.h> # define LIBSSH2_STRUCT_STAT_SIZE_FORMAT "%I64d" typedef struct _stati64 libssh2_struct_stat; typedef __int64 libssh2_struct_stat_size; #endif /* * Small file (<2Gb) support using WIN32 functions. */ #ifdef LIBSSH2_USE_WIN32_SMALL_FILES # include <sys/types.h> # include <sys/stat.h> # ifndef _WIN32_WCE # define LIBSSH2_STRUCT_STAT_SIZE_FORMAT "%d" typedef struct _stat libssh2_struct_stat; typedef off_t libssh2_struct_stat_size; # endif #endif #ifndef LIBSSH2_STRUCT_STAT_SIZE_FORMAT # ifdef __VMS /* We have to roll our own format here because %z is a C99-ism we don't have. */ # if __USE_OFF64_T || __USING_STD_STAT # define LIBSSH2_STRUCT_STAT_SIZE_FORMAT "%Ld" # else # define LIBSSH2_STRUCT_STAT_SIZE_FORMAT "%d" # endif # else # define LIBSSH2_STRUCT_STAT_SIZE_FORMAT "%zd" # endif typedef struct stat libssh2_struct_stat; typedef off_t libssh2_struct_stat_size; #endif /* Part of every banner, user specified or not */ #define LIBSSH2_SSH_BANNER "SSH-2.0-libssh2_" LIBSSH2_VERSION /* We *could* add a comment here if we so chose */ #define LIBSSH2_SSH_DEFAULT_BANNER LIBSSH2_SSH_BANNER #define LIBSSH2_SSH_DEFAULT_BANNER_WITH_CRLF LIBSSH2_SSH_DEFAULT_BANNER "\r\n" /* Default generate and safe prime sizes for diffie-hellman-group-exchange-sha1 */ #define LIBSSH2_DH_GEX_MINGROUP 1024 #define LIBSSH2_DH_GEX_OPTGROUP 1536 #define LIBSSH2_DH_GEX_MAXGROUP 2048 /* Defaults for pty requests */ #define LIBSSH2_TERM_WIDTH 80 #define LIBSSH2_TERM_HEIGHT 24 #define LIBSSH2_TERM_WIDTH_PX 0 #define LIBSSH2_TERM_HEIGHT_PX 0 /* 1/4 second */ #define LIBSSH2_SOCKET_POLL_UDELAY 250000 /* 0.25 * 120 == 30 seconds */ #define LIBSSH2_SOCKET_POLL_MAXLOOPS 120 /* Maximum size to allow a payload to compress to, plays it safe by falling short of spec limits */ #define LIBSSH2_PACKET_MAXCOMP 32000 /* Maximum size to allow a payload to deccompress to, plays it safe by allowing more than spec requires */ #define LIBSSH2_PACKET_MAXDECOMP 40000 /* Maximum size for an inbound compressed payload, plays it safe by overshooting spec limits */ #define LIBSSH2_PACKET_MAXPAYLOAD 40000 /* Malloc callbacks */ #define LIBSSH2_ALLOC_FUNC(name) void *name(size_t count, void **abstract) #define LIBSSH2_REALLOC_FUNC(name) void *name(void *ptr, size_t count, \ void **abstract) #define LIBSSH2_FREE_FUNC(name) void name(void *ptr, void **abstract) typedef struct _LIBSSH2_USERAUTH_KBDINT_PROMPT { char* text; unsigned int length; unsigned char echo; } LIBSSH2_USERAUTH_KBDINT_PROMPT; typedef struct _LIBSSH2_USERAUTH_KBDINT_RESPONSE { char* text; unsigned int length; } LIBSSH2_USERAUTH_KBDINT_RESPONSE; /* 'publickey' authentication callback */ #define LIBSSH2_USERAUTH_PUBLICKEY_SIGN_FUNC(name) \ int name(LIBSSH2_SESSION *session, unsigned char **sig, size_t *sig_len, \ const unsigned char *data, size_t data_len, void **abstract) /* 'keyboard-interactive' authentication callback */ #define LIBSSH2_USERAUTH_KBDINT_RESPONSE_FUNC(name_) \ void name_(const char* name, int name_len, const char* instruction, \ int instruction_len, int num_prompts, \ const LIBSSH2_USERAUTH_KBDINT_PROMPT* prompts, \ LIBSSH2_USERAUTH_KBDINT_RESPONSE* responses, void **abstract) /* Callbacks for special SSH packets */ #define LIBSSH2_IGNORE_FUNC(name) \ void name(LIBSSH2_SESSION *session, const char *message, int message_len, \ void **abstract) #define LIBSSH2_DEBUG_FUNC(name) \ void name(LIBSSH2_SESSION *session, int always_display, const char *message, \ int message_len, const char *language, int language_len, \ void **abstract) #define LIBSSH2_DISCONNECT_FUNC(name) \ void name(LIBSSH2_SESSION *session, int reason, const char *message, \ int message_len, const char *language, int language_len, \ void **abstract) #define LIBSSH2_PASSWD_CHANGEREQ_FUNC(name) \ void name(LIBSSH2_SESSION *session, char **newpw, int *newpw_len, \ void **abstract) #define LIBSSH2_MACERROR_FUNC(name) \ int name(LIBSSH2_SESSION *session, const char *packet, int packet_len, \ void **abstract) #define LIBSSH2_X11_OPEN_FUNC(name) \ void name(LIBSSH2_SESSION *session, LIBSSH2_CHANNEL *channel, \ const char *shost, int sport, void **abstract) #define LIBSSH2_CHANNEL_CLOSE_FUNC(name) \ void name(LIBSSH2_SESSION *session, void **session_abstract, \ LIBSSH2_CHANNEL *channel, void **channel_abstract) /* I/O callbacks */ #define LIBSSH2_RECV_FUNC(name) ssize_t name(libssh2_socket_t socket, \ void *buffer, size_t length, \ int flags, void **abstract) #define LIBSSH2_SEND_FUNC(name) ssize_t name(libssh2_socket_t socket, \ const void *buffer, size_t length,\ int flags, void **abstract) /* libssh2_session_callback_set() constants */ #define LIBSSH2_CALLBACK_IGNORE 0 #define LIBSSH2_CALLBACK_DEBUG 1 #define LIBSSH2_CALLBACK_DISCONNECT 2 #define LIBSSH2_CALLBACK_MACERROR 3 #define LIBSSH2_CALLBACK_X11 4 #define LIBSSH2_CALLBACK_SEND 5 #define LIBSSH2_CALLBACK_RECV 6 /* libssh2_session_method_pref() constants */ #define LIBSSH2_METHOD_KEX 0 #define LIBSSH2_METHOD_HOSTKEY 1 #define LIBSSH2_METHOD_CRYPT_CS 2 #define LIBSSH2_METHOD_CRYPT_SC 3 #define LIBSSH2_METHOD_MAC_CS 4 #define LIBSSH2_METHOD_MAC_SC 5 #define LIBSSH2_METHOD_COMP_CS 6 #define LIBSSH2_METHOD_COMP_SC 7 #define LIBSSH2_METHOD_LANG_CS 8 #define LIBSSH2_METHOD_LANG_SC 9 /* flags */ #define LIBSSH2_FLAG_SIGPIPE 1 #define LIBSSH2_FLAG_COMPRESS 2 typedef struct _LIBSSH2_SESSION LIBSSH2_SESSION; typedef struct _LIBSSH2_CHANNEL LIBSSH2_CHANNEL; typedef struct _LIBSSH2_LISTENER LIBSSH2_LISTENER; typedef struct _LIBSSH2_KNOWNHOSTS LIBSSH2_KNOWNHOSTS; typedef struct _LIBSSH2_AGENT LIBSSH2_AGENT; typedef struct _LIBSSH2_POLLFD { unsigned char type; /* LIBSSH2_POLLFD_* below */ union { libssh2_socket_t socket; /* File descriptors -- examined with system select() call */ LIBSSH2_CHANNEL *channel; /* Examined by checking internal state */ LIBSSH2_LISTENER *listener; /* Read polls only -- are inbound connections waiting to be accepted? */ } fd; unsigned long events; /* Requested Events */ unsigned long revents; /* Returned Events */ } LIBSSH2_POLLFD; /* Poll FD Descriptor Types */ #define LIBSSH2_POLLFD_SOCKET 1 #define LIBSSH2_POLLFD_CHANNEL 2 #define LIBSSH2_POLLFD_LISTENER 3 /* Note: Win32 Doesn't actually have a poll() implementation, so some of these values are faked with select() data */ /* Poll FD events/revents -- Match sys/poll.h where possible */ #define LIBSSH2_POLLFD_POLLIN 0x0001 /* Data available to be read or connection available -- All */ #define LIBSSH2_POLLFD_POLLPRI 0x0002 /* Priority data available to be read -- Socket only */ #define LIBSSH2_POLLFD_POLLEXT 0x0002 /* Extended data available to be read -- Channel only */ #define LIBSSH2_POLLFD_POLLOUT 0x0004 /* Can may be written -- Socket/Channel */ /* revents only */ #define LIBSSH2_POLLFD_POLLERR 0x0008 /* Error Condition -- Socket */ #define LIBSSH2_POLLFD_POLLHUP 0x0010 /* HangUp/EOF -- Socket */ #define LIBSSH2_POLLFD_SESSION_CLOSED 0x0010 /* Session Disconnect */ #define LIBSSH2_POLLFD_POLLNVAL 0x0020 /* Invalid request -- Socket Only */ #define LIBSSH2_POLLFD_POLLEX 0x0040 /* Exception Condition -- Socket/Win32 */ #define LIBSSH2_POLLFD_CHANNEL_CLOSED 0x0080 /* Channel Disconnect */ #define LIBSSH2_POLLFD_LISTENER_CLOSED 0x0080 /* Listener Disconnect */ #define HAVE_LIBSSH2_SESSION_BLOCK_DIRECTION /* Block Direction Types */ #define LIBSSH2_SESSION_BLOCK_INBOUND 0x0001 #define LIBSSH2_SESSION_BLOCK_OUTBOUND 0x0002 /* Hash Types */ #define LIBSSH2_HOSTKEY_HASH_MD5 1 #define LIBSSH2_HOSTKEY_HASH_SHA1 2 /* Hostkey Types */ #define LIBSSH2_HOSTKEY_TYPE_UNKNOWN 0 #define LIBSSH2_HOSTKEY_TYPE_RSA 1 #define LIBSSH2_HOSTKEY_TYPE_DSS 2 /* Disconnect Codes (defined by SSH protocol) */ #define SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 #define SSH_DISCONNECT_PROTOCOL_ERROR 2 #define SSH_DISCONNECT_KEY_EXCHANGE_FAILED 3 #define SSH_DISCONNECT_RESERVED 4 #define SSH_DISCONNECT_MAC_ERROR 5 #define SSH_DISCONNECT_COMPRESSION_ERROR 6 #define SSH_DISCONNECT_SERVICE_NOT_AVAILABLE 7 #define SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 #define SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 #define SSH_DISCONNECT_CONNECTION_LOST 10 #define SSH_DISCONNECT_BY_APPLICATION 11 #define SSH_DISCONNECT_TOO_MANY_CONNECTIONS 12 #define SSH_DISCONNECT_AUTH_CANCELLED_BY_USER 13 #define SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 #define SSH_DISCONNECT_ILLEGAL_USER_NAME 15 /* Error Codes (defined by libssh2) */ #define LIBSSH2_ERROR_NONE 0 /* The library once used -1 as a generic error return value on numerous places through the code, which subsequently was converted to LIBSSH2_ERROR_SOCKET_NONE uses over time. As this is a generic error code, the goal is to never ever return this code but instead make sure that a more accurate and descriptive error code is used. */ #define LIBSSH2_ERROR_SOCKET_NONE -1 #define LIBSSH2_ERROR_BANNER_RECV -2 #define LIBSSH2_ERROR_BANNER_SEND -3 #define LIBSSH2_ERROR_INVALID_MAC -4 #define LIBSSH2_ERROR_KEX_FAILURE -5 #define LIBSSH2_ERROR_ALLOC -6 #define LIBSSH2_ERROR_SOCKET_SEND -7 #define LIBSSH2_ERROR_KEY_EXCHANGE_FAILURE -8 #define LIBSSH2_ERROR_TIMEOUT -9 #define LIBSSH2_ERROR_HOSTKEY_INIT -10 #define LIBSSH2_ERROR_HOSTKEY_SIGN -11 #define LIBSSH2_ERROR_DECRYPT -12 #define LIBSSH2_ERROR_SOCKET_DISCONNECT -13 #define LIBSSH2_ERROR_PROTO -14 #define LIBSSH2_ERROR_PASSWORD_EXPIRED -15 #define LIBSSH2_ERROR_FILE -16 #define LIBSSH2_ERROR_METHOD_NONE -17 #define LIBSSH2_ERROR_AUTHENTICATION_FAILED -18 #define LIBSSH2_ERROR_PUBLICKEY_UNRECOGNIZED LIBSSH2_ERROR_AUTHENTICATION_FAILED #define LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED -19 #define LIBSSH2_ERROR_CHANNEL_OUTOFORDER -20 #define LIBSSH2_ERROR_CHANNEL_FAILURE -21 #define LIBSSH2_ERROR_CHANNEL_REQUEST_DENIED -22 #define LIBSSH2_ERROR_CHANNEL_UNKNOWN -23 #define LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED -24 #define LIBSSH2_ERROR_CHANNEL_PACKET_EXCEEDED -25 #define LIBSSH2_ERROR_CHANNEL_CLOSED -26 #define LIBSSH2_ERROR_CHANNEL_EOF_SENT -27 #define LIBSSH2_ERROR_SCP_PROTOCOL -28 #define LIBSSH2_ERROR_ZLIB -29 #define LIBSSH2_ERROR_SOCKET_TIMEOUT -30 #define LIBSSH2_ERROR_SFTP_PROTOCOL -31 #define LIBSSH2_ERROR_REQUEST_DENIED -32 #define LIBSSH2_ERROR_METHOD_NOT_SUPPORTED -33 #define LIBSSH2_ERROR_INVAL -34 #define LIBSSH2_ERROR_INVALID_POLL_TYPE -35 #define LIBSSH2_ERROR_PUBLICKEY_PROTOCOL -36 #define LIBSSH2_ERROR_EAGAIN -37 #define LIBSSH2_ERROR_BUFFER_TOO_SMALL -38 #define LIBSSH2_ERROR_BAD_USE -39 #define LIBSSH2_ERROR_COMPRESS -40 #define LIBSSH2_ERROR_OUT_OF_BOUNDARY -41 #define LIBSSH2_ERROR_AGENT_PROTOCOL -42 #define LIBSSH2_ERROR_SOCKET_RECV -43 #define LIBSSH2_ERROR_ENCRYPT -44 #define LIBSSH2_ERROR_BAD_SOCKET -45 #define LIBSSH2_ERROR_KNOWN_HOSTS -46 /* this is a define to provide the old (<= 1.2.7) name */ #define LIBSSH2_ERROR_BANNER_NONE LIBSSH2_ERROR_BANNER_RECV /* Global API */ #define LIBSSH2_INIT_NO_CRYPTO 0x0001 /* * libssh2_init() * * Initialize the libssh2 functions. This typically initialize the * crypto library. It uses a global state, and is not thread safe -- * you must make sure this function is not called concurrently. * * Flags can be: * 0: Normal initialize * LIBSSH2_INIT_NO_CRYPTO: Do not initialize the crypto library (ie. * OPENSSL_add_cipher_algoritms() for OpenSSL * * Returns 0 if succeeded, or a negative value for error. */ LIBSSH2_API int libssh2_init(int flags); /* * libssh2_exit() * * Exit the libssh2 functions and free's all memory used internal. */ LIBSSH2_API void libssh2_exit(void); /* * libssh2_free() * * Deallocate memory allocated by earlier call to libssh2 functions. */ LIBSSH2_API void libssh2_free(LIBSSH2_SESSION *session, void *ptr); /* * libssh2_session_supported_algs() * * Fills algs with a list of supported acryptographic algorithms. Returns a * non-negative number (number of supported algorithms) on success or a * negative number (an eror code) on failure. * * NOTE: on success, algs must be deallocated (by calling libssh2_free) when * not needed anymore */ LIBSSH2_API int libssh2_session_supported_algs(LIBSSH2_SESSION* session, int method_type, const char*** algs); /* Session API */ LIBSSH2_API LIBSSH2_SESSION * libssh2_session_init_ex(LIBSSH2_ALLOC_FUNC((*my_alloc)), LIBSSH2_FREE_FUNC((*my_free)), LIBSSH2_REALLOC_FUNC((*my_realloc)), void *abstract); #define libssh2_session_init() libssh2_session_init_ex(NULL, NULL, NULL, NULL) LIBSSH2_API void **libssh2_session_abstract(LIBSSH2_SESSION *session); LIBSSH2_API void *libssh2_session_callback_set(LIBSSH2_SESSION *session, int cbtype, void *callback); LIBSSH2_API int libssh2_session_banner_set(LIBSSH2_SESSION *session, const char *banner); LIBSSH2_API int libssh2_banner_set(LIBSSH2_SESSION *session, const char *banner); LIBSSH2_API int libssh2_session_startup(LIBSSH2_SESSION *session, int sock); LIBSSH2_API int libssh2_session_handshake(LIBSSH2_SESSION *session, libssh2_socket_t sock); LIBSSH2_API int libssh2_session_disconnect_ex(LIBSSH2_SESSION *session, int reason, const char *description, const char *lang); #define libssh2_session_disconnect(session, description) \ libssh2_session_disconnect_ex((session), SSH_DISCONNECT_BY_APPLICATION, \ (description), "") LIBSSH2_API int libssh2_session_free(LIBSSH2_SESSION *session); LIBSSH2_API const char *libssh2_hostkey_hash(LIBSSH2_SESSION *session, int hash_type); LIBSSH2_API const char *libssh2_session_hostkey(LIBSSH2_SESSION *session, size_t *len, int *type); LIBSSH2_API int libssh2_session_method_pref(LIBSSH2_SESSION *session, int method_type, const char *prefs); LIBSSH2_API const char *libssh2_session_methods(LIBSSH2_SESSION *session, int method_type); LIBSSH2_API int libssh2_session_last_error(LIBSSH2_SESSION *session, char **errmsg, int *errmsg_len, int want_buf); LIBSSH2_API int libssh2_session_last_errno(LIBSSH2_SESSION *session); LIBSSH2_API int libssh2_session_set_last_error(LIBSSH2_SESSION* session, int errcode, const char* errmsg); LIBSSH2_API int libssh2_session_block_directions(LIBSSH2_SESSION *session); LIBSSH2_API int libssh2_session_flag(LIBSSH2_SESSION *session, int flag, int value); LIBSSH2_API const char *libssh2_session_banner_get(LIBSSH2_SESSION *session); /* Userauth API */ LIBSSH2_API char *libssh2_userauth_list(LIBSSH2_SESSION *session, const char *username, unsigned int username_len); LIBSSH2_API int libssh2_userauth_authenticated(LIBSSH2_SESSION *session); LIBSSH2_API int libssh2_userauth_password_ex(LIBSSH2_SESSION *session, const char *username, unsigned int username_len, const char *password, unsigned int password_len, LIBSSH2_PASSWD_CHANGEREQ_FUNC((*passwd_change_cb))); #define libssh2_userauth_password(session, username, password) \ libssh2_userauth_password_ex((session), (username), \ (unsigned int)strlen(username), \ (password), (unsigned int)strlen(password), NULL) LIBSSH2_API int libssh2_userauth_publickey_fromfile_ex(LIBSSH2_SESSION *session, const char *username, unsigned int username_len, const char *publickey, const char *privatekey, const char *passphrase); #define libssh2_userauth_publickey_fromfile(session, username, publickey, \ privatekey, passphrase) \ libssh2_userauth_publickey_fromfile_ex((session), (username), \ (unsigned int)strlen(username), \ (publickey), \ (privatekey), (passphrase)) LIBSSH2_API int libssh2_userauth_publickey(LIBSSH2_SESSION *session, const char *username, const unsigned char *pubkeydata, size_t pubkeydata_len, LIBSSH2_USERAUTH_PUBLICKEY_SIGN_FUNC((*sign_callback)), void **abstract); LIBSSH2_API int libssh2_userauth_hostbased_fromfile_ex(LIBSSH2_SESSION *session, const char *username, unsigned int username_len, const char *publickey, const char *privatekey, const char *passphrase, const char *hostname, unsigned int hostname_len, const char *local_username, unsigned int local_username_len); #define libssh2_userauth_hostbased_fromfile(session, username, publickey, \ privatekey, passphrase, hostname) \ libssh2_userauth_hostbased_fromfile_ex((session), (username), \ (unsigned int)strlen(username), \ (publickey), \ (privatekey), (passphrase), \ (hostname), \ (unsigned int)strlen(hostname), \ (username), \ (unsigned int)strlen(username)) LIBSSH2_API int libssh2_userauth_publickey_frommemory(LIBSSH2_SESSION *session, const char *username, size_t username_len, const char *publickeyfiledata, size_t publickeyfiledata_len, const char *privatekeyfiledata, size_t privatekeyfiledata_len, const char *passphrase); /* * response_callback is provided with filled by library prompts array, * but client must allocate and fill individual responses. Responses * array is already allocated. Responses data will be freed by libssh2 * after callback return, but before subsequent callback invokation. */ LIBSSH2_API int libssh2_userauth_keyboard_interactive_ex(LIBSSH2_SESSION* session, const char *username, unsigned int username_len, LIBSSH2_USERAUTH_KBDINT_RESPONSE_FUNC( (*response_callback))); #define libssh2_userauth_keyboard_interactive(session, username, \ response_callback) \ libssh2_userauth_keyboard_interactive_ex((session), (username), \ (unsigned int)strlen(username), \ (response_callback)) LIBSSH2_API int libssh2_poll(LIBSSH2_POLLFD *fds, unsigned int nfds, long timeout); /* Channel API */ #define LIBSSH2_CHANNEL_WINDOW_DEFAULT (2*1024*1024) #define LIBSSH2_CHANNEL_PACKET_DEFAULT 32768 #define LIBSSH2_CHANNEL_MINADJUST 1024 /* Extended Data Handling */ #define LIBSSH2_CHANNEL_EXTENDED_DATA_NORMAL 0 #define LIBSSH2_CHANNEL_EXTENDED_DATA_IGNORE 1 #define LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE 2 #define SSH_EXTENDED_DATA_STDERR 1 /* Returned by any function that would block during a read/write opperation */ #define LIBSSH2CHANNEL_EAGAIN LIBSSH2_ERROR_EAGAIN LIBSSH2_API LIBSSH2_CHANNEL * libssh2_channel_open_ex(LIBSSH2_SESSION *session, const char *channel_type, unsigned int channel_type_len, unsigned int window_size, unsigned int packet_size, const char *message, unsigned int message_len); #define libssh2_channel_open_session(session) \ libssh2_channel_open_ex((session), "session", sizeof("session") - 1, \ LIBSSH2_CHANNEL_WINDOW_DEFAULT, \ LIBSSH2_CHANNEL_PACKET_DEFAULT, NULL, 0) LIBSSH2_API LIBSSH2_CHANNEL * libssh2_channel_direct_tcpip_ex(LIBSSH2_SESSION *session, const char *host, int port, const char *shost, int sport); #define libssh2_channel_direct_tcpip(session, host, port) \ libssh2_channel_direct_tcpip_ex((session), (host), (port), "127.0.0.1", 22) LIBSSH2_API LIBSSH2_LISTENER * libssh2_channel_forward_listen_ex(LIBSSH2_SESSION *session, const char *host, int port, int *bound_port, int queue_maxsize); #define libssh2_channel_forward_listen(session, port) \ libssh2_channel_forward_listen_ex((session), NULL, (port), NULL, 16) LIBSSH2_API int libssh2_channel_forward_cancel(LIBSSH2_LISTENER *listener); LIBSSH2_API LIBSSH2_CHANNEL * libssh2_channel_forward_accept(LIBSSH2_LISTENER *listener); LIBSSH2_API int libssh2_channel_setenv_ex(LIBSSH2_CHANNEL *channel, const char *varname, unsigned int varname_len, const char *value, unsigned int value_len); #define libssh2_channel_setenv(channel, varname, value) \ libssh2_channel_setenv_ex((channel), (varname), \ (unsigned int)strlen(varname), (value), \ (unsigned int)strlen(value)) LIBSSH2_API int libssh2_channel_request_pty_ex(LIBSSH2_CHANNEL *channel, const char *term, unsigned int term_len, const char *modes, unsigned int modes_len, int width, int height, int width_px, int height_px); #define libssh2_channel_request_pty(channel, term) \ libssh2_channel_request_pty_ex((channel), (term), \ (unsigned int)strlen(term), \ NULL, 0, \ LIBSSH2_TERM_WIDTH, LIBSSH2_TERM_HEIGHT, \ LIBSSH2_TERM_WIDTH_PX, LIBSSH2_TERM_HEIGHT_PX) LIBSSH2_API int libssh2_channel_request_pty_size_ex(LIBSSH2_CHANNEL *channel, int width, int height, int width_px, int height_px); #define libssh2_channel_request_pty_size(channel, width, height) \ libssh2_channel_request_pty_size_ex( (channel), (width), (height), 0, 0) LIBSSH2_API int libssh2_channel_x11_req_ex(LIBSSH2_CHANNEL *channel, int single_connection, const char *auth_proto, const char *auth_cookie, int screen_number); #define libssh2_channel_x11_req(channel, screen_number) \ libssh2_channel_x11_req_ex((channel), 0, NULL, NULL, (screen_number)) LIBSSH2_API int libssh2_channel_process_startup(LIBSSH2_CHANNEL *channel, const char *request, unsigned int request_len, const char *message, unsigned int message_len); #define libssh2_channel_shell(channel) \ libssh2_channel_process_startup((channel), "shell", sizeof("shell") - 1, \ NULL, 0) #define libssh2_channel_exec(channel, command) \ libssh2_channel_process_startup((channel), "exec", sizeof("exec") - 1, \ (command), (unsigned int)strlen(command)) #define libssh2_channel_subsystem(channel, subsystem) \ libssh2_channel_process_startup((channel), "subsystem", \ sizeof("subsystem") - 1, (subsystem), \ (unsigned int)strlen(subsystem)) LIBSSH2_API ssize_t libssh2_channel_read_ex(LIBSSH2_CHANNEL *channel, int stream_id, char *buf, size_t buflen); #define libssh2_channel_read(channel, buf, buflen) \ libssh2_channel_read_ex((channel), 0, (buf), (buflen)) #define libssh2_channel_read_stderr(channel, buf, buflen) \ libssh2_channel_read_ex((channel), SSH_EXTENDED_DATA_STDERR, (buf), (buflen)) LIBSSH2_API int libssh2_poll_channel_read(LIBSSH2_CHANNEL *channel, int extended); LIBSSH2_API unsigned long libssh2_channel_window_read_ex(LIBSSH2_CHANNEL *channel, unsigned long *read_avail, unsigned long *window_size_initial); #define libssh2_channel_window_read(channel) \ libssh2_channel_window_read_ex((channel), NULL, NULL) /* libssh2_channel_receive_window_adjust is DEPRECATED, do not use! */ LIBSSH2_API unsigned long libssh2_channel_receive_window_adjust(LIBSSH2_CHANNEL *channel, unsigned long adjustment, unsigned char force); LIBSSH2_API int libssh2_channel_receive_window_adjust2(LIBSSH2_CHANNEL *channel, unsigned long adjustment, unsigned char force, unsigned int *storewindow); LIBSSH2_API ssize_t libssh2_channel_write_ex(LIBSSH2_CHANNEL *channel, int stream_id, const char *buf, size_t buflen); #define libssh2_channel_write(channel, buf, buflen) \ libssh2_channel_write_ex((channel), 0, (buf), (buflen)) #define libssh2_channel_write_stderr(channel, buf, buflen) \ libssh2_channel_write_ex((channel), SSH_EXTENDED_DATA_STDERR, (buf), (buflen)) LIBSSH2_API unsigned long libssh2_channel_window_write_ex(LIBSSH2_CHANNEL *channel, unsigned long *window_size_initial); #define libssh2_channel_window_write(channel) \ libssh2_channel_window_write_ex((channel), NULL) LIBSSH2_API void libssh2_session_set_blocking(LIBSSH2_SESSION* session, int blocking); LIBSSH2_API int libssh2_session_get_blocking(LIBSSH2_SESSION* session); LIBSSH2_API void libssh2_channel_set_blocking(LIBSSH2_CHANNEL *channel, int blocking); LIBSSH2_API void libssh2_session_set_timeout(LIBSSH2_SESSION* session, long timeout); LIBSSH2_API long libssh2_session_get_timeout(LIBSSH2_SESSION* session); /* libssh2_channel_handle_extended_data is DEPRECATED, do not use! */ LIBSSH2_API void libssh2_channel_handle_extended_data(LIBSSH2_CHANNEL *channel, int ignore_mode); LIBSSH2_API int libssh2_channel_handle_extended_data2(LIBSSH2_CHANNEL *channel, int ignore_mode); /* libssh2_channel_ignore_extended_data() is defined below for BC with version * 0.1 * * Future uses should use libssh2_channel_handle_extended_data() directly if * LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE is passed, extended data will be read * (FIFO) from the standard data channel */ /* DEPRECATED */ #define libssh2_channel_ignore_extended_data(channel, ignore) \ libssh2_channel_handle_extended_data((channel), \ (ignore) ? \ LIBSSH2_CHANNEL_EXTENDED_DATA_IGNORE : \ LIBSSH2_CHANNEL_EXTENDED_DATA_NORMAL ) #define LIBSSH2_CHANNEL_FLUSH_EXTENDED_DATA -1 #define LIBSSH2_CHANNEL_FLUSH_ALL -2 LIBSSH2_API int libssh2_channel_flush_ex(LIBSSH2_CHANNEL *channel, int streamid); #define libssh2_channel_flush(channel) libssh2_channel_flush_ex((channel), 0) #define libssh2_channel_flush_stderr(channel) \ libssh2_channel_flush_ex((channel), SSH_EXTENDED_DATA_STDERR) LIBSSH2_API int libssh2_channel_get_exit_status(LIBSSH2_CHANNEL* channel); LIBSSH2_API int libssh2_channel_get_exit_signal(LIBSSH2_CHANNEL* channel, char **exitsignal, size_t *exitsignal_len, char **errmsg, size_t *errmsg_len, char **langtag, size_t *langtag_len); LIBSSH2_API int libssh2_channel_send_eof(LIBSSH2_CHANNEL *channel); LIBSSH2_API int libssh2_channel_eof(LIBSSH2_CHANNEL *channel); LIBSSH2_API int libssh2_channel_wait_eof(LIBSSH2_CHANNEL *channel); LIBSSH2_API int libssh2_channel_close(LIBSSH2_CHANNEL *channel); LIBSSH2_API int libssh2_channel_wait_closed(LIBSSH2_CHANNEL *channel); LIBSSH2_API int libssh2_channel_free(LIBSSH2_CHANNEL *channel); /* libssh2_scp_recv is DEPRECATED, do not use! */ LIBSSH2_API LIBSSH2_CHANNEL *libssh2_scp_recv(LIBSSH2_SESSION *session, const char *path, struct stat *sb); /* Use libssh2_scp_recv2 for large (> 2GB) file support on windows */ LIBSSH2_API LIBSSH2_CHANNEL *libssh2_scp_recv2(LIBSSH2_SESSION *session, const char *path, libssh2_struct_stat *sb); LIBSSH2_API LIBSSH2_CHANNEL *libssh2_scp_send_ex(LIBSSH2_SESSION *session, const char *path, int mode, size_t size, long mtime, long atime); LIBSSH2_API LIBSSH2_CHANNEL * libssh2_scp_send64(LIBSSH2_SESSION *session, const char *path, int mode, libssh2_int64_t size, time_t mtime, time_t atime); #define libssh2_scp_send(session, path, mode, size) \ libssh2_scp_send_ex((session), (path), (mode), (size), 0, 0) LIBSSH2_API int libssh2_base64_decode(LIBSSH2_SESSION *session, char **dest, unsigned int *dest_len, const char *src, unsigned int src_len); LIBSSH2_API const char *libssh2_version(int req_version_num); #define HAVE_LIBSSH2_KNOWNHOST_API 0x010101 /* since 1.1.1 */ #define HAVE_LIBSSH2_VERSION_API 0x010100 /* libssh2_version since 1.1 */ struct libssh2_knownhost { unsigned int magic; /* magic stored by the library */ void *node; /* handle to the internal representation of this host */ char *name; /* this is NULL if no plain text host name exists */ char *key; /* key in base64/printable format */ int typemask; }; /* * libssh2_knownhost_init * * Init a collection of known hosts. Returns the pointer to a collection. * */ LIBSSH2_API LIBSSH2_KNOWNHOSTS * libssh2_knownhost_init(LIBSSH2_SESSION *session); /* * libssh2_knownhost_add * * Add a host and its associated key to the collection of known hosts. * * The 'type' argument specifies on what format the given host and keys are: * * plain - ascii "hostname.domain.tld" * sha1 - SHA1(<salt> <host>) base64-encoded! * custom - another hash * * If 'sha1' is selected as type, the salt must be provided to the salt * argument. This too base64 encoded. * * The SHA-1 hash is what OpenSSH can be told to use in known_hosts files. If * a custom type is used, salt is ignored and you must provide the host * pre-hashed when checking for it in the libssh2_knownhost_check() function. * * The keylen parameter may be omitted (zero) if the key is provided as a * NULL-terminated base64-encoded string. */ /* host format (2 bits) */ #define LIBSSH2_KNOWNHOST_TYPE_MASK 0xffff #define LIBSSH2_KNOWNHOST_TYPE_PLAIN 1 #define LIBSSH2_KNOWNHOST_TYPE_SHA1 2 /* always base64 encoded */ #define LIBSSH2_KNOWNHOST_TYPE_CUSTOM 3 /* key format (2 bits) */ #define LIBSSH2_KNOWNHOST_KEYENC_MASK (3<<16) #define LIBSSH2_KNOWNHOST_KEYENC_RAW (1<<16) #define LIBSSH2_KNOWNHOST_KEYENC_BASE64 (2<<16) /* type of key (2 bits) */ #define LIBSSH2_KNOWNHOST_KEY_MASK (7<<18) #define LIBSSH2_KNOWNHOST_KEY_SHIFT 18 #define LIBSSH2_KNOWNHOST_KEY_RSA1 (1<<18) #define LIBSSH2_KNOWNHOST_KEY_SSHRSA (2<<18) #define LIBSSH2_KNOWNHOST_KEY_SSHDSS (3<<18) #define LIBSSH2_KNOWNHOST_KEY_UNKNOWN (7<<18) LIBSSH2_API int libssh2_knownhost_add(LIBSSH2_KNOWNHOSTS *hosts, const char *host, const char *salt, const char *key, size_t keylen, int typemask, struct libssh2_knownhost **store); /* * libssh2_knownhost_addc * * Add a host and its associated key to the collection of known hosts. * * Takes a comment argument that may be NULL. A NULL comment indicates * there is no comment and the entry will end directly after the key * when written out to a file. An empty string "" comment will indicate an * empty comment which will cause a single space to be written after the key. * * The 'type' argument specifies on what format the given host and keys are: * * plain - ascii "hostname.domain.tld" * sha1 - SHA1(<salt> <host>) base64-encoded! * custom - another hash * * If 'sha1' is selected as type, the salt must be provided to the salt * argument. This too base64 encoded. * * The SHA-1 hash is what OpenSSH can be told to use in known_hosts files. If * a custom type is used, salt is ignored and you must provide the host * pre-hashed when checking for it in the libssh2_knownhost_check() function. * * The keylen parameter may be omitted (zero) if the key is provided as a * NULL-terminated base64-encoded string. */ LIBSSH2_API int libssh2_knownhost_addc(LIBSSH2_KNOWNHOSTS *hosts, const char *host, const char *salt, const char *key, size_t keylen, const char *comment, size_t commentlen, int typemask, struct libssh2_knownhost **store); /* * libssh2_knownhost_check * * Check a host and its associated key against the collection of known hosts. * * The type is the type/format of the given host name. * * plain - ascii "hostname.domain.tld" * custom - prehashed base64 encoded. Note that this cannot use any salts. * * * 'knownhost' may be set to NULL if you don't care about that info. * * Returns: * * LIBSSH2_KNOWNHOST_CHECK_* values, see below * */ #define LIBSSH2_KNOWNHOST_CHECK_MATCH 0 #define LIBSSH2_KNOWNHOST_CHECK_MISMATCH 1 #define LIBSSH2_KNOWNHOST_CHECK_NOTFOUND 2 #define LIBSSH2_KNOWNHOST_CHECK_FAILURE 3 LIBSSH2_API int libssh2_knownhost_check(LIBSSH2_KNOWNHOSTS *hosts, const char *host, const char *key, size_t keylen, int typemask, struct libssh2_knownhost **knownhost); /* this function is identital to the above one, but also takes a port argument that allows libssh2 to do a better check */ LIBSSH2_API int libssh2_knownhost_checkp(LIBSSH2_KNOWNHOSTS *hosts, const char *host, int port, const char *key, size_t keylen, int typemask, struct libssh2_knownhost **knownhost); /* * libssh2_knownhost_del * * Remove a host from the collection of known hosts. The 'entry' struct is * retrieved by a call to libssh2_knownhost_check(). * */ LIBSSH2_API int libssh2_knownhost_del(LIBSSH2_KNOWNHOSTS *hosts, struct libssh2_knownhost *entry); /* * libssh2_knownhost_free * * Free an entire collection of known hosts. * */ LIBSSH2_API void libssh2_knownhost_free(LIBSSH2_KNOWNHOSTS *hosts); /* * libssh2_knownhost_readline() * * Pass in a line of a file of 'type'. It makes libssh2 read this line. * * LIBSSH2_KNOWNHOST_FILE_OPENSSH is the only supported type. * */ LIBSSH2_API int libssh2_knownhost_readline(LIBSSH2_KNOWNHOSTS *hosts, const char *line, size_t len, int type); /* * libssh2_knownhost_readfile * * Add hosts+key pairs from a given file. * * Returns a negative value for error or number of successfully added hosts. * * This implementation currently only knows one 'type' (openssh), all others * are reserved for future use. */ #define LIBSSH2_KNOWNHOST_FILE_OPENSSH 1 LIBSSH2_API int libssh2_knownhost_readfile(LIBSSH2_KNOWNHOSTS *hosts, const char *filename, int type); /* * libssh2_knownhost_writeline() * * Ask libssh2 to convert a known host to an output line for storage. * * Note that this function returns LIBSSH2_ERROR_BUFFER_TOO_SMALL if the given * output buffer is too small to hold the desired output. * * This implementation currently only knows one 'type' (openssh), all others * are reserved for future use. * */ LIBSSH2_API int libssh2_knownhost_writeline(LIBSSH2_KNOWNHOSTS *hosts, struct libssh2_knownhost *known, char *buffer, size_t buflen, size_t *outlen, /* the amount of written data */ int type); /* * libssh2_knownhost_writefile * * Write hosts+key pairs to a given file. * * This implementation currently only knows one 'type' (openssh), all others * are reserved for future use. */ LIBSSH2_API int libssh2_knownhost_writefile(LIBSSH2_KNOWNHOSTS *hosts, const char *filename, int type); /* * libssh2_knownhost_get() * * Traverse the internal list of known hosts. Pass NULL to 'prev' to get * the first one. Or pass a poiner to the previously returned one to get the * next. * * Returns: * 0 if a fine host was stored in 'store' * 1 if end of hosts * [negative] on errors */ LIBSSH2_API int libssh2_knownhost_get(LIBSSH2_KNOWNHOSTS *hosts, struct libssh2_knownhost **store, struct libssh2_knownhost *prev); #define HAVE_LIBSSH2_AGENT_API 0x010202 /* since 1.2.2 */ struct libssh2_agent_publickey { unsigned int magic; /* magic stored by the library */ void *node; /* handle to the internal representation of key */ unsigned char *blob; /* public key blob */ size_t blob_len; /* length of the public key blob */ char *comment; /* comment in printable format */ }; /* * libssh2_agent_init * * Init an ssh-agent handle. Returns the pointer to the handle. * */ LIBSSH2_API LIBSSH2_AGENT * libssh2_agent_init(LIBSSH2_SESSION *session); /* * libssh2_agent_connect() * * Connect to an ssh-agent. * * Returns 0 if succeeded, or a negative value for error. */ LIBSSH2_API int libssh2_agent_connect(LIBSSH2_AGENT *agent); /* * libssh2_agent_list_identities() * * Request an ssh-agent to list identities. * * Returns 0 if succeeded, or a negative value for error. */ LIBSSH2_API int libssh2_agent_list_identities(LIBSSH2_AGENT *agent); /* * libssh2_agent_get_identity() * * Traverse the internal list of public keys. Pass NULL to 'prev' to get * the first one. Or pass a poiner to the previously returned one to get the * next. * * Returns: * 0 if a fine public key was stored in 'store' * 1 if end of public keys * [negative] on errors */ LIBSSH2_API int libssh2_agent_get_identity(LIBSSH2_AGENT *agent, struct libssh2_agent_publickey **store, struct libssh2_agent_publickey *prev); /* * libssh2_agent_userauth() * * Do publickey user authentication with the help of ssh-agent. * * Returns 0 if succeeded, or a negative value for error. */ LIBSSH2_API int libssh2_agent_userauth(LIBSSH2_AGENT *agent, const char *username, struct libssh2_agent_publickey *identity); /* * libssh2_agent_disconnect() * * Close a connection to an ssh-agent. * * Returns 0 if succeeded, or a negative value for error. */ LIBSSH2_API int libssh2_agent_disconnect(LIBSSH2_AGENT *agent); /* * libssh2_agent_free() * * Free an ssh-agent handle. This function also frees the internal * collection of public keys. */ LIBSSH2_API void libssh2_agent_free(LIBSSH2_AGENT *agent); /* * libssh2_keepalive_config() * * Set how often keepalive messages should be sent. WANT_REPLY * indicates whether the keepalive messages should request a response * from the server. INTERVAL is number of seconds that can pass * without any I/O, use 0 (the default) to disable keepalives. To * avoid some busy-loop corner-cases, if you specify an interval of 1 * it will be treated as 2. * * Note that non-blocking applications are responsible for sending the * keepalive messages using libssh2_keepalive_send(). */ LIBSSH2_API void libssh2_keepalive_config (LIBSSH2_SESSION *session, int want_reply, unsigned interval); /* * libssh2_keepalive_send() * * Send a keepalive message if needed. SECONDS_TO_NEXT indicates how * many seconds you can sleep after this call before you need to call * it again. Returns 0 on success, or LIBSSH2_ERROR_SOCKET_SEND on * I/O errors. */ LIBSSH2_API int libssh2_keepalive_send (LIBSSH2_SESSION *session, int *seconds_to_next); /* NOTE NOTE NOTE libssh2_trace() has no function in builds that aren't built with debug enabled */ LIBSSH2_API int libssh2_trace(LIBSSH2_SESSION *session, int bitmask); #define LIBSSH2_TRACE_TRANS (1<<1) #define LIBSSH2_TRACE_KEX (1<<2) #define LIBSSH2_TRACE_AUTH (1<<3) #define LIBSSH2_TRACE_CONN (1<<4) #define LIBSSH2_TRACE_SCP (1<<5) #define LIBSSH2_TRACE_SFTP (1<<6) #define LIBSSH2_TRACE_ERROR (1<<7) #define LIBSSH2_TRACE_PUBLICKEY (1<<8) #define LIBSSH2_TRACE_SOCKET (1<<9) typedef void (*libssh2_trace_handler_func)(LIBSSH2_SESSION*, void*, const char *, size_t); LIBSSH2_API int libssh2_trace_sethandler(LIBSSH2_SESSION *session, void* context, libssh2_trace_handler_func callback); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* !RC_INVOKED */ #endif /* LIBSSH2_H */
52,417
C++
.h
1,126
37.797513
97
0.621442
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,267
libssh2_sftp.h
Studio3T_robomongo/src/third-party/libssh2-1.7.0/sources/include/libssh2_sftp.h
/* Copyright (c) 2004-2008, Sara Golemon <sarag@libssh2.org> * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifndef LIBSSH2_SFTP_H #define LIBSSH2_SFTP_H 1 #include "libssh2.h" #ifndef WIN32 #include <unistd.h> #endif #ifdef __cplusplus extern "C" { #endif /* Note: Version 6 was documented at the time of writing * However it was marked as "DO NOT IMPLEMENT" due to pending changes * * Let's start with Version 3 (The version found in OpenSSH) and go from there */ #define LIBSSH2_SFTP_VERSION 3 typedef struct _LIBSSH2_SFTP LIBSSH2_SFTP; typedef struct _LIBSSH2_SFTP_HANDLE LIBSSH2_SFTP_HANDLE; typedef struct _LIBSSH2_SFTP_ATTRIBUTES LIBSSH2_SFTP_ATTRIBUTES; typedef struct _LIBSSH2_SFTP_STATVFS LIBSSH2_SFTP_STATVFS; /* Flags for open_ex() */ #define LIBSSH2_SFTP_OPENFILE 0 #define LIBSSH2_SFTP_OPENDIR 1 /* Flags for rename_ex() */ #define LIBSSH2_SFTP_RENAME_OVERWRITE 0x00000001 #define LIBSSH2_SFTP_RENAME_ATOMIC 0x00000002 #define LIBSSH2_SFTP_RENAME_NATIVE 0x00000004 /* Flags for stat_ex() */ #define LIBSSH2_SFTP_STAT 0 #define LIBSSH2_SFTP_LSTAT 1 #define LIBSSH2_SFTP_SETSTAT 2 /* Flags for symlink_ex() */ #define LIBSSH2_SFTP_SYMLINK 0 #define LIBSSH2_SFTP_READLINK 1 #define LIBSSH2_SFTP_REALPATH 2 /* SFTP attribute flag bits */ #define LIBSSH2_SFTP_ATTR_SIZE 0x00000001 #define LIBSSH2_SFTP_ATTR_UIDGID 0x00000002 #define LIBSSH2_SFTP_ATTR_PERMISSIONS 0x00000004 #define LIBSSH2_SFTP_ATTR_ACMODTIME 0x00000008 #define LIBSSH2_SFTP_ATTR_EXTENDED 0x80000000 /* SFTP statvfs flag bits */ #define LIBSSH2_SFTP_ST_RDONLY 0x00000001 #define LIBSSH2_SFTP_ST_NOSUID 0x00000002 struct _LIBSSH2_SFTP_ATTRIBUTES { /* If flags & ATTR_* bit is set, then the value in this struct will be * meaningful Otherwise it should be ignored */ unsigned long flags; libssh2_uint64_t filesize; unsigned long uid, gid; unsigned long permissions; unsigned long atime, mtime; }; struct _LIBSSH2_SFTP_STATVFS { libssh2_uint64_t f_bsize; /* file system block size */ libssh2_uint64_t f_frsize; /* fragment size */ libssh2_uint64_t f_blocks; /* size of fs in f_frsize units */ libssh2_uint64_t f_bfree; /* # free blocks */ libssh2_uint64_t f_bavail; /* # free blocks for non-root */ libssh2_uint64_t f_files; /* # inodes */ libssh2_uint64_t f_ffree; /* # free inodes */ libssh2_uint64_t f_favail; /* # free inodes for non-root */ libssh2_uint64_t f_fsid; /* file system ID */ libssh2_uint64_t f_flag; /* mount flags */ libssh2_uint64_t f_namemax; /* maximum filename length */ }; /* SFTP filetypes */ #define LIBSSH2_SFTP_TYPE_REGULAR 1 #define LIBSSH2_SFTP_TYPE_DIRECTORY 2 #define LIBSSH2_SFTP_TYPE_SYMLINK 3 #define LIBSSH2_SFTP_TYPE_SPECIAL 4 #define LIBSSH2_SFTP_TYPE_UNKNOWN 5 #define LIBSSH2_SFTP_TYPE_SOCKET 6 #define LIBSSH2_SFTP_TYPE_CHAR_DEVICE 7 #define LIBSSH2_SFTP_TYPE_BLOCK_DEVICE 8 #define LIBSSH2_SFTP_TYPE_FIFO 9 /* * Reproduce the POSIX file modes here for systems that are not POSIX * compliant. * * These is used in "permissions" of "struct _LIBSSH2_SFTP_ATTRIBUTES" */ /* File type */ #define LIBSSH2_SFTP_S_IFMT 0170000 /* type of file mask */ #define LIBSSH2_SFTP_S_IFIFO 0010000 /* named pipe (fifo) */ #define LIBSSH2_SFTP_S_IFCHR 0020000 /* character special */ #define LIBSSH2_SFTP_S_IFDIR 0040000 /* directory */ #define LIBSSH2_SFTP_S_IFBLK 0060000 /* block special */ #define LIBSSH2_SFTP_S_IFREG 0100000 /* regular */ #define LIBSSH2_SFTP_S_IFLNK 0120000 /* symbolic link */ #define LIBSSH2_SFTP_S_IFSOCK 0140000 /* socket */ /* File mode */ /* Read, write, execute/search by owner */ #define LIBSSH2_SFTP_S_IRWXU 0000700 /* RWX mask for owner */ #define LIBSSH2_SFTP_S_IRUSR 0000400 /* R for owner */ #define LIBSSH2_SFTP_S_IWUSR 0000200 /* W for owner */ #define LIBSSH2_SFTP_S_IXUSR 0000100 /* X for owner */ /* Read, write, execute/search by group */ #define LIBSSH2_SFTP_S_IRWXG 0000070 /* RWX mask for group */ #define LIBSSH2_SFTP_S_IRGRP 0000040 /* R for group */ #define LIBSSH2_SFTP_S_IWGRP 0000020 /* W for group */ #define LIBSSH2_SFTP_S_IXGRP 0000010 /* X for group */ /* Read, write, execute/search by others */ #define LIBSSH2_SFTP_S_IRWXO 0000007 /* RWX mask for other */ #define LIBSSH2_SFTP_S_IROTH 0000004 /* R for other */ #define LIBSSH2_SFTP_S_IWOTH 0000002 /* W for other */ #define LIBSSH2_SFTP_S_IXOTH 0000001 /* X for other */ /* macros to check for specific file types, added in 1.2.5 */ #define LIBSSH2_SFTP_S_ISLNK(m) \ (((m) & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFLNK) #define LIBSSH2_SFTP_S_ISREG(m) \ (((m) & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFREG) #define LIBSSH2_SFTP_S_ISDIR(m) \ (((m) & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFDIR) #define LIBSSH2_SFTP_S_ISCHR(m) \ (((m) & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFCHR) #define LIBSSH2_SFTP_S_ISBLK(m) \ (((m) & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFBLK) #define LIBSSH2_SFTP_S_ISFIFO(m) \ (((m) & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFIFO) #define LIBSSH2_SFTP_S_ISSOCK(m) \ (((m) & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFSOCK) /* SFTP File Transfer Flags -- (e.g. flags parameter to sftp_open()) * Danger will robinson... APPEND doesn't have any effect on OpenSSH servers */ #define LIBSSH2_FXF_READ 0x00000001 #define LIBSSH2_FXF_WRITE 0x00000002 #define LIBSSH2_FXF_APPEND 0x00000004 #define LIBSSH2_FXF_CREAT 0x00000008 #define LIBSSH2_FXF_TRUNC 0x00000010 #define LIBSSH2_FXF_EXCL 0x00000020 /* SFTP Status Codes (returned by libssh2_sftp_last_error() ) */ #define LIBSSH2_FX_OK 0 #define LIBSSH2_FX_EOF 1 #define LIBSSH2_FX_NO_SUCH_FILE 2 #define LIBSSH2_FX_PERMISSION_DENIED 3 #define LIBSSH2_FX_FAILURE 4 #define LIBSSH2_FX_BAD_MESSAGE 5 #define LIBSSH2_FX_NO_CONNECTION 6 #define LIBSSH2_FX_CONNECTION_LOST 7 #define LIBSSH2_FX_OP_UNSUPPORTED 8 #define LIBSSH2_FX_INVALID_HANDLE 9 #define LIBSSH2_FX_NO_SUCH_PATH 10 #define LIBSSH2_FX_FILE_ALREADY_EXISTS 11 #define LIBSSH2_FX_WRITE_PROTECT 12 #define LIBSSH2_FX_NO_MEDIA 13 #define LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM 14 #define LIBSSH2_FX_QUOTA_EXCEEDED 15 #define LIBSSH2_FX_UNKNOWN_PRINCIPLE 16 /* Initial mis-spelling */ #define LIBSSH2_FX_UNKNOWN_PRINCIPAL 16 #define LIBSSH2_FX_LOCK_CONFlICT 17 /* Initial mis-spelling */ #define LIBSSH2_FX_LOCK_CONFLICT 17 #define LIBSSH2_FX_DIR_NOT_EMPTY 18 #define LIBSSH2_FX_NOT_A_DIRECTORY 19 #define LIBSSH2_FX_INVALID_FILENAME 20 #define LIBSSH2_FX_LINK_LOOP 21 /* Returned by any function that would block during a read/write opperation */ #define LIBSSH2SFTP_EAGAIN LIBSSH2_ERROR_EAGAIN /* SFTP API */ LIBSSH2_API LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session); LIBSSH2_API int libssh2_sftp_shutdown(LIBSSH2_SFTP *sftp); LIBSSH2_API unsigned long libssh2_sftp_last_error(LIBSSH2_SFTP *sftp); LIBSSH2_API LIBSSH2_CHANNEL *libssh2_sftp_get_channel(LIBSSH2_SFTP *sftp); /* File / Directory Ops */ LIBSSH2_API LIBSSH2_SFTP_HANDLE *libssh2_sftp_open_ex(LIBSSH2_SFTP *sftp, const char *filename, unsigned int filename_len, unsigned long flags, long mode, int open_type); #define libssh2_sftp_open(sftp, filename, flags, mode) \ libssh2_sftp_open_ex((sftp), (filename), strlen(filename), (flags), \ (mode), LIBSSH2_SFTP_OPENFILE) #define libssh2_sftp_opendir(sftp, path) \ libssh2_sftp_open_ex((sftp), (path), strlen(path), 0, 0, \ LIBSSH2_SFTP_OPENDIR) LIBSSH2_API ssize_t libssh2_sftp_read(LIBSSH2_SFTP_HANDLE *handle, char *buffer, size_t buffer_maxlen); LIBSSH2_API int libssh2_sftp_readdir_ex(LIBSSH2_SFTP_HANDLE *handle, \ char *buffer, size_t buffer_maxlen, char *longentry, size_t longentry_maxlen, LIBSSH2_SFTP_ATTRIBUTES *attrs); #define libssh2_sftp_readdir(handle, buffer, buffer_maxlen, attrs) \ libssh2_sftp_readdir_ex((handle), (buffer), (buffer_maxlen), NULL, 0, \ (attrs)) LIBSSH2_API ssize_t libssh2_sftp_write(LIBSSH2_SFTP_HANDLE *handle, const char *buffer, size_t count); LIBSSH2_API int libssh2_sftp_fsync(LIBSSH2_SFTP_HANDLE *handle); LIBSSH2_API int libssh2_sftp_close_handle(LIBSSH2_SFTP_HANDLE *handle); #define libssh2_sftp_close(handle) libssh2_sftp_close_handle(handle) #define libssh2_sftp_closedir(handle) libssh2_sftp_close_handle(handle) LIBSSH2_API void libssh2_sftp_seek(LIBSSH2_SFTP_HANDLE *handle, size_t offset); LIBSSH2_API void libssh2_sftp_seek64(LIBSSH2_SFTP_HANDLE *handle, libssh2_uint64_t offset); #define libssh2_sftp_rewind(handle) libssh2_sftp_seek64((handle), 0) LIBSSH2_API size_t libssh2_sftp_tell(LIBSSH2_SFTP_HANDLE *handle); LIBSSH2_API libssh2_uint64_t libssh2_sftp_tell64(LIBSSH2_SFTP_HANDLE *handle); LIBSSH2_API int libssh2_sftp_fstat_ex(LIBSSH2_SFTP_HANDLE *handle, LIBSSH2_SFTP_ATTRIBUTES *attrs, int setstat); #define libssh2_sftp_fstat(handle, attrs) \ libssh2_sftp_fstat_ex((handle), (attrs), 0) #define libssh2_sftp_fsetstat(handle, attrs) \ libssh2_sftp_fstat_ex((handle), (attrs), 1) /* Miscellaneous Ops */ LIBSSH2_API int libssh2_sftp_rename_ex(LIBSSH2_SFTP *sftp, const char *source_filename, unsigned int srouce_filename_len, const char *dest_filename, unsigned int dest_filename_len, long flags); #define libssh2_sftp_rename(sftp, sourcefile, destfile) \ libssh2_sftp_rename_ex((sftp), (sourcefile), strlen(sourcefile), \ (destfile), strlen(destfile), \ LIBSSH2_SFTP_RENAME_OVERWRITE | \ LIBSSH2_SFTP_RENAME_ATOMIC | \ LIBSSH2_SFTP_RENAME_NATIVE) LIBSSH2_API int libssh2_sftp_unlink_ex(LIBSSH2_SFTP *sftp, const char *filename, unsigned int filename_len); #define libssh2_sftp_unlink(sftp, filename) \ libssh2_sftp_unlink_ex((sftp), (filename), strlen(filename)) LIBSSH2_API int libssh2_sftp_fstatvfs(LIBSSH2_SFTP_HANDLE *handle, LIBSSH2_SFTP_STATVFS *st); LIBSSH2_API int libssh2_sftp_statvfs(LIBSSH2_SFTP *sftp, const char *path, size_t path_len, LIBSSH2_SFTP_STATVFS *st); LIBSSH2_API int libssh2_sftp_mkdir_ex(LIBSSH2_SFTP *sftp, const char *path, unsigned int path_len, long mode); #define libssh2_sftp_mkdir(sftp, path, mode) \ libssh2_sftp_mkdir_ex((sftp), (path), strlen(path), (mode)) LIBSSH2_API int libssh2_sftp_rmdir_ex(LIBSSH2_SFTP *sftp, const char *path, unsigned int path_len); #define libssh2_sftp_rmdir(sftp, path) \ libssh2_sftp_rmdir_ex((sftp), (path), strlen(path)) LIBSSH2_API int libssh2_sftp_stat_ex(LIBSSH2_SFTP *sftp, const char *path, unsigned int path_len, int stat_type, LIBSSH2_SFTP_ATTRIBUTES *attrs); #define libssh2_sftp_stat(sftp, path, attrs) \ libssh2_sftp_stat_ex((sftp), (path), strlen(path), LIBSSH2_SFTP_STAT, \ (attrs)) #define libssh2_sftp_lstat(sftp, path, attrs) \ libssh2_sftp_stat_ex((sftp), (path), strlen(path), LIBSSH2_SFTP_LSTAT, \ (attrs)) #define libssh2_sftp_setstat(sftp, path, attrs) \ libssh2_sftp_stat_ex((sftp), (path), strlen(path), LIBSSH2_SFTP_SETSTAT, \ (attrs)) LIBSSH2_API int libssh2_sftp_symlink_ex(LIBSSH2_SFTP *sftp, const char *path, unsigned int path_len, char *target, unsigned int target_len, int link_type); #define libssh2_sftp_symlink(sftp, orig, linkpath) \ libssh2_sftp_symlink_ex((sftp), (orig), strlen(orig), (linkpath), \ strlen(linkpath), LIBSSH2_SFTP_SYMLINK) #define libssh2_sftp_readlink(sftp, path, target, maxlen) \ libssh2_sftp_symlink_ex((sftp), (path), strlen(path), (target), (maxlen), \ LIBSSH2_SFTP_READLINK) #define libssh2_sftp_realpath(sftp, path, target, maxlen) \ libssh2_sftp_symlink_ex((sftp), (path), strlen(path), (target), (maxlen), \ LIBSSH2_SFTP_REALPATH) #ifdef __cplusplus } /* extern "C" */ #endif #endif /* LIBSSH2_SFTP_H */
15,716
C++
.h
305
43.947541
80
0.621991
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,268
crypto.h
Studio3T_robomongo/src/third-party/libssh2-1.7.0/sources/src/crypto.h
/* Copyright (C) 2009, 2010 Simon Josefsson * Copyright (C) 2006, 2007 The Written Word, Inc. All rights reserved. * Copyright (C) 2010 Daniel Stenberg * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifndef LIBSSH2_CRYPTO_H #define LIBSSH2_CRYPTO_H #ifdef LIBSSH2_OPENSSL #include "openssl.h" #endif #ifdef LIBSSH2_LIBGCRYPT #include "libgcrypt.h" #endif #ifdef LIBSSH2_WINCNG #include "wincng.h" #endif #ifdef LIBSSH2_OS400QC3 #include "os400qc3.h" #endif int _libssh2_rsa_new(libssh2_rsa_ctx ** rsa, const unsigned char *edata, unsigned long elen, const unsigned char *ndata, unsigned long nlen, const unsigned char *ddata, unsigned long dlen, const unsigned char *pdata, unsigned long plen, const unsigned char *qdata, unsigned long qlen, const unsigned char *e1data, unsigned long e1len, const unsigned char *e2data, unsigned long e2len, const unsigned char *coeffdata, unsigned long coefflen); int _libssh2_rsa_new_private(libssh2_rsa_ctx ** rsa, LIBSSH2_SESSION * session, const char *filename, unsigned const char *passphrase); int _libssh2_rsa_sha1_verify(libssh2_rsa_ctx * rsa, const unsigned char *sig, unsigned long sig_len, const unsigned char *m, unsigned long m_len); int _libssh2_rsa_sha1_sign(LIBSSH2_SESSION * session, libssh2_rsa_ctx * rsactx, const unsigned char *hash, size_t hash_len, unsigned char **signature, size_t *signature_len); int _libssh2_rsa_new_private_frommemory(libssh2_rsa_ctx ** rsa, LIBSSH2_SESSION * session, const char *filedata, size_t filedata_len, unsigned const char *passphrase); #if LIBSSH2_DSA int _libssh2_dsa_new(libssh2_dsa_ctx ** dsa, const unsigned char *pdata, unsigned long plen, const unsigned char *qdata, unsigned long qlen, const unsigned char *gdata, unsigned long glen, const unsigned char *ydata, unsigned long ylen, const unsigned char *x, unsigned long x_len); int _libssh2_dsa_new_private(libssh2_dsa_ctx ** dsa, LIBSSH2_SESSION * session, const char *filename, unsigned const char *passphrase); int _libssh2_dsa_sha1_verify(libssh2_dsa_ctx * dsactx, const unsigned char *sig, const unsigned char *m, unsigned long m_len); int _libssh2_dsa_sha1_sign(libssh2_dsa_ctx * dsactx, const unsigned char *hash, unsigned long hash_len, unsigned char *sig); int _libssh2_dsa_new_private_frommemory(libssh2_dsa_ctx ** dsa, LIBSSH2_SESSION * session, const char *filedata, size_t filedata_len, unsigned const char *passphrase); #endif int _libssh2_cipher_init(_libssh2_cipher_ctx * h, _libssh2_cipher_type(algo), unsigned char *iv, unsigned char *secret, int encrypt); int _libssh2_cipher_crypt(_libssh2_cipher_ctx * ctx, _libssh2_cipher_type(algo), int encrypt, unsigned char *block, size_t blocksize); int _libssh2_pub_priv_keyfile(LIBSSH2_SESSION *session, unsigned char **method, size_t *method_len, unsigned char **pubkeydata, size_t *pubkeydata_len, const char *privatekey, const char *passphrase); int _libssh2_pub_priv_keyfilememory(LIBSSH2_SESSION *session, unsigned char **method, size_t *method_len, unsigned char **pubkeydata, size_t *pubkeydata_len, const char *privatekeydata, size_t privatekeydata_len, const char *passphrase); void _libssh2_init_aes_ctr(void); #endif
6,459
C++
.h
135
33.081481
82
0.561064
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,269
wincng.h
Studio3T_robomongo/src/third-party/libssh2-1.7.0/sources/src/wincng.h
/* * Copyright (C) 2013-2015 Marc Hoersken <info@marc-hoersken.de> * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ /* required for cross-compilation against the w64 mingw-runtime package */ #if defined(_WIN32_WINNT) && (_WIN32_WINNT < 0x0600) #undef _WIN32_WINNT #endif #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0600 #endif #include <windows.h> #include <bcrypt.h> #define LIBSSH2_MD5 1 #define LIBSSH2_HMAC_RIPEMD 0 #define LIBSSH2_HMAC_SHA256 1 #define LIBSSH2_HMAC_SHA512 1 #define LIBSSH2_AES 1 #define LIBSSH2_AES_CTR 0 #define LIBSSH2_BLOWFISH 0 #define LIBSSH2_RC4 1 #define LIBSSH2_CAST 0 #define LIBSSH2_3DES 1 #define LIBSSH2_RSA 1 #define LIBSSH2_DSA 1 #define MD5_DIGEST_LENGTH 16 #define SHA_DIGEST_LENGTH 20 #define SHA256_DIGEST_LENGTH 32 #define SHA512_DIGEST_LENGTH 64 /*******************************************************************/ /* * Windows CNG backend: Global context handles */ struct _libssh2_wincng_ctx { BCRYPT_ALG_HANDLE hAlgRNG; BCRYPT_ALG_HANDLE hAlgHashMD5; BCRYPT_ALG_HANDLE hAlgHashSHA1; BCRYPT_ALG_HANDLE hAlgHashSHA256; BCRYPT_ALG_HANDLE hAlgHashSHA512; BCRYPT_ALG_HANDLE hAlgHmacMD5; BCRYPT_ALG_HANDLE hAlgHmacSHA1; BCRYPT_ALG_HANDLE hAlgHmacSHA256; BCRYPT_ALG_HANDLE hAlgHmacSHA512; BCRYPT_ALG_HANDLE hAlgRSA; BCRYPT_ALG_HANDLE hAlgDSA; BCRYPT_ALG_HANDLE hAlgAES_CBC; BCRYPT_ALG_HANDLE hAlgRC4_NA; BCRYPT_ALG_HANDLE hAlg3DES_CBC; }; struct _libssh2_wincng_ctx _libssh2_wincng; /*******************************************************************/ /* * Windows CNG backend: Generic functions */ void _libssh2_wincng_init(void); void _libssh2_wincng_free(void); #define libssh2_crypto_init() \ _libssh2_wincng_init() #define libssh2_crypto_exit() \ _libssh2_wincng_free() #define _libssh2_random(buf, len) \ _libssh2_wincng_random(buf, len) #define libssh2_prepare_iovec(vec, len) /* Empty. */ /*******************************************************************/ /* * Windows CNG backend: Hash structure */ typedef struct __libssh2_wincng_hash_ctx { BCRYPT_HASH_HANDLE hHash; unsigned char *pbHashObject; unsigned long dwHashObject; unsigned long cbHash; } _libssh2_wincng_hash_ctx; /* * Windows CNG backend: Hash functions */ #define libssh2_sha1_ctx _libssh2_wincng_hash_ctx #define libssh2_sha1_init(ctx) \ (_libssh2_wincng_hash_init(ctx, _libssh2_wincng.hAlgHashSHA1, \ SHA_DIGEST_LENGTH, NULL, 0) == 0) #define libssh2_sha1_update(ctx, data, datalen) \ _libssh2_wincng_hash_update(&ctx, (unsigned char *) data, datalen) #define libssh2_sha1_final(ctx, hash) \ _libssh2_wincng_hash_final(&ctx, hash) #define libssh2_sha1(data, datalen, hash) \ _libssh2_wincng_hash(data, datalen, _libssh2_wincng.hAlgHashSHA1, \ hash, SHA_DIGEST_LENGTH) #define libssh2_sha256_ctx _libssh2_wincng_hash_ctx #define libssh2_sha256_init(ctx) \ (_libssh2_wincng_hash_init(ctx, _libssh2_wincng.hAlgHashSHA256, \ SHA256_DIGEST_LENGTH, NULL, 0) == 0) #define libssh2_sha256_update(ctx, data, datalen) \ _libssh2_wincng_hash_update(&ctx, (unsigned char *) data, datalen) #define libssh2_sha256_final(ctx, hash) \ _libssh2_wincng_hash_final(&ctx, hash) #define libssh2_sha256(data, datalen, hash) \ _libssh2_wincng_hash(data, datalen, _libssh2_wincng.hAlgHashSHA256, \ hash, SHA256_DIGEST_LENGTH) #define libssh2_sha512_ctx _libssh2_wincng_hash_ctx #define libssh2_sha512_init(ctx) \ (_libssh2_wincng_hash_init(ctx, _libssh2_wincng.hAlgHashSHA512, \ SHA512_DIGEST_LENGTH, NULL, 0) == 0) #define libssh2_sha512_update(ctx, data, datalen) \ _libssh2_wincng_hash_update(&ctx, (unsigned char *) data, datalen) #define libssh2_sha512_final(ctx, hash) \ _libssh2_wincng_hash_final(&ctx, hash) #define libssh2_sha512(data, datalen, hash) \ _libssh2_wincng_hash(data, datalen, _libssh2_wincng.hAlgHashSHA512, \ hash, SHA512_DIGEST_LENGTH) #define libssh2_md5_ctx _libssh2_wincng_hash_ctx #define libssh2_md5_init(ctx) \ (_libssh2_wincng_hash_init(ctx, _libssh2_wincng.hAlgHashMD5, \ MD5_DIGEST_LENGTH, NULL, 0) == 0) #define libssh2_md5_update(ctx, data, datalen) \ _libssh2_wincng_hash_update(&ctx, (unsigned char *) data, datalen) #define libssh2_md5_final(ctx, hash) \ _libssh2_wincng_hash_final(&ctx, hash) #define libssh2_md5(data, datalen, hash) \ _libssh2_wincng_hash(data, datalen, _libssh2_wincng.hAlgHashMD5, \ hash, MD5_DIGEST_LENGTH) /* * Windows CNG backend: HMAC functions */ #define libssh2_hmac_ctx _libssh2_wincng_hash_ctx #define libssh2_hmac_ctx_init(ctx) #define libssh2_hmac_sha1_init(ctx, key, keylen) \ _libssh2_wincng_hash_init(ctx, _libssh2_wincng.hAlgHmacSHA1, \ SHA_DIGEST_LENGTH, key, keylen) #define libssh2_hmac_md5_init(ctx, key, keylen) \ _libssh2_wincng_hash_init(ctx, _libssh2_wincng.hAlgHmacMD5, \ MD5_DIGEST_LENGTH, key, keylen) #define libssh2_hmac_ripemd160_init(ctx, key, keylen) /* not implemented */ #define libssh2_hmac_sha256_init(ctx, key, keylen) \ _libssh2_wincng_hash_init(ctx, _libssh2_wincng.hAlgHmacSHA256, \ SHA256_DIGEST_LENGTH, key, keylen) #define libssh2_hmac_sha512_init(ctx, key, keylen) \ _libssh2_wincng_hash_init(ctx, _libssh2_wincng.hAlgHmacSHA512, \ SHA512_DIGEST_LENGTH, key, keylen) #define libssh2_hmac_update(ctx, data, datalen) \ _libssh2_wincng_hash_update(&ctx, (unsigned char *) data, datalen) #define libssh2_hmac_final(ctx, hash) \ _libssh2_wincng_hmac_final(&ctx, hash) #define libssh2_hmac_cleanup(ctx) \ _libssh2_wincng_hmac_cleanup(ctx) /*******************************************************************/ /* * Windows CNG backend: Key Context structure */ typedef struct __libssh2_wincng_key_ctx { BCRYPT_KEY_HANDLE hKey; unsigned char *pbKeyObject; unsigned long cbKeyObject; } _libssh2_wincng_key_ctx; /* * Windows CNG backend: RSA functions */ #define libssh2_rsa_ctx _libssh2_wincng_key_ctx #define _libssh2_rsa_new(rsactx, e, e_len, n, n_len, \ d, d_len, p, p_len, q, q_len, \ e1, e1_len, e2, e2_len, c, c_len) \ _libssh2_wincng_rsa_new(rsactx, e, e_len, n, n_len, \ d, d_len, p, p_len, q, q_len, \ e1, e1_len, e2, e2_len, c, c_len) #define _libssh2_rsa_new_private(rsactx, s, filename, passphrase) \ _libssh2_wincng_rsa_new_private(rsactx, s, filename, passphrase) #define _libssh2_rsa_new_private_frommemory(rsactx, s, filedata, \ filedata_len, passphrase) \ _libssh2_wincng_rsa_new_private_frommemory(rsactx, s, filedata, \ filedata_len, passphrase) #define _libssh2_rsa_sha1_sign(s, rsactx, hash, hash_len, sig, sig_len) \ _libssh2_wincng_rsa_sha1_sign(s, rsactx, hash, hash_len, sig, sig_len) #define _libssh2_rsa_sha1_verify(rsactx, sig, sig_len, m, m_len) \ _libssh2_wincng_rsa_sha1_verify(rsactx, sig, sig_len, m, m_len) #define _libssh2_rsa_free(rsactx) \ _libssh2_wincng_rsa_free(rsactx) /* * Windows CNG backend: DSA functions */ #define libssh2_dsa_ctx _libssh2_wincng_key_ctx #define _libssh2_dsa_new(dsactx, p, p_len, q, q_len, \ g, g_len, y, y_len, x, x_len) \ _libssh2_wincng_dsa_new(dsactx, p, p_len, q, q_len, \ g, g_len, y, y_len, x, x_len) #define _libssh2_dsa_new_private(dsactx, s, filename, passphrase) \ _libssh2_wincng_dsa_new_private(dsactx, s, filename, passphrase) #define _libssh2_dsa_new_private_frommemory(dsactx, s, filedata, \ filedata_len, passphrase) \ _libssh2_wincng_dsa_new_private_frommemory(dsactx, s, filedata, \ filedata_len, passphrase) #define _libssh2_dsa_sha1_sign(dsactx, hash, hash_len, sig) \ _libssh2_wincng_dsa_sha1_sign(dsactx, hash, hash_len, sig) #define _libssh2_dsa_sha1_verify(dsactx, sig, m, m_len) \ _libssh2_wincng_dsa_sha1_verify(dsactx, sig, m, m_len) #define _libssh2_dsa_free(dsactx) \ _libssh2_wincng_dsa_free(dsactx) /* * Windows CNG backend: Key functions */ #define _libssh2_pub_priv_keyfile(s, m, m_len, p, p_len, pk, pw) \ _libssh2_wincng_pub_priv_keyfile(s, m, m_len, p, p_len, pk, pw) #define _libssh2_pub_priv_keyfilememory(s, m, m_len, p, p_len, \ pk, pk_len, pw) \ _libssh2_wincng_pub_priv_keyfilememory(s, m, m_len, p, p_len, \ pk, pk_len, pw) /*******************************************************************/ /* * Windows CNG backend: Cipher Context structure */ struct _libssh2_wincng_cipher_ctx { BCRYPT_KEY_HANDLE hKey; unsigned char *pbKeyObject; unsigned char *pbIV; unsigned long dwKeyObject; unsigned long dwIV; unsigned long dwBlockLength; }; #define _libssh2_cipher_ctx struct _libssh2_wincng_cipher_ctx /* * Windows CNG backend: Cipher Type structure */ struct _libssh2_wincng_cipher_type { BCRYPT_ALG_HANDLE *phAlg; unsigned long dwKeyLength; unsigned long dwUseIV; }; #define _libssh2_cipher_type(type) struct _libssh2_wincng_cipher_type type #define _libssh2_cipher_aes256ctr { NULL, 32, 1 } /* not supported */ #define _libssh2_cipher_aes192ctr { NULL, 24, 1 } /* not supported */ #define _libssh2_cipher_aes128ctr { NULL, 16, 1 } /* not supported */ #define _libssh2_cipher_aes256 { &_libssh2_wincng.hAlgAES_CBC, 32, 1 } #define _libssh2_cipher_aes192 { &_libssh2_wincng.hAlgAES_CBC, 24, 1 } #define _libssh2_cipher_aes128 { &_libssh2_wincng.hAlgAES_CBC, 16, 1 } #define _libssh2_cipher_blowfish { NULL, 16, 0 } /* not supported */ #define _libssh2_cipher_arcfour { &_libssh2_wincng.hAlgRC4_NA, 16, 0 } #define _libssh2_cipher_cast5 { NULL, 16, 0 } /* not supported */ #define _libssh2_cipher_3des { &_libssh2_wincng.hAlg3DES_CBC, 24, 1 } /* * Windows CNG backend: Cipher functions */ #define _libssh2_cipher_init(ctx, type, iv, secret, encrypt) \ _libssh2_wincng_cipher_init(ctx, type, iv, secret, encrypt) #define _libssh2_cipher_crypt(ctx, type, encrypt, block, blocklen) \ _libssh2_wincng_cipher_crypt(ctx, type, encrypt, block, blocklen) #define _libssh2_cipher_dtor(ctx) \ _libssh2_wincng_cipher_dtor(ctx) /*******************************************************************/ /* * Windows CNG backend: BigNumber Context */ #define _libssh2_bn_ctx int /* not used */ #define _libssh2_bn_ctx_new() 0 /* not used */ #define _libssh2_bn_ctx_free(bnctx) ((void)0) /* not used */ /*******************************************************************/ /* * Windows CNG backend: BigNumber structure */ struct _libssh2_wincng_bignum { unsigned char *bignum; unsigned long length; }; #define _libssh2_bn struct _libssh2_wincng_bignum /* * Windows CNG backend: BigNumber functions */ _libssh2_bn *_libssh2_wincng_bignum_init(void); #define _libssh2_bn_init() \ _libssh2_wincng_bignum_init() #define _libssh2_bn_init_from_bin() \ _libssh2_bn_init() #define _libssh2_bn_rand(bn, bits, top, bottom) \ _libssh2_wincng_bignum_rand(bn, bits, top, bottom) #define _libssh2_bn_mod_exp(r, a, p, m, ctx) \ _libssh2_wincng_bignum_mod_exp(r, a, p, m, ctx) #define _libssh2_bn_set_word(bn, word) \ _libssh2_wincng_bignum_set_word(bn, word) #define _libssh2_bn_from_bin(bn, len, bin) \ _libssh2_wincng_bignum_from_bin(bn, len, bin) #define _libssh2_bn_to_bin(bn, bin) \ _libssh2_wincng_bignum_to_bin(bn, bin) #define _libssh2_bn_bytes(bn) bn->length #define _libssh2_bn_bits(bn) \ _libssh2_wincng_bignum_bits(bn) #define _libssh2_bn_free(bn) \ _libssh2_wincng_bignum_free(bn) /*******************************************************************/ /* * Windows CNG backend: forward declarations */ void _libssh2_wincng_init(void); void _libssh2_wincng_free(void); int _libssh2_wincng_random(void *buf, int len); void _libssh2_init_aes_ctr(void); int _libssh2_wincng_hash_init(_libssh2_wincng_hash_ctx *ctx, BCRYPT_ALG_HANDLE hAlg, unsigned long hashlen, unsigned char *key, unsigned long keylen); int _libssh2_wincng_hash_update(_libssh2_wincng_hash_ctx *ctx, const unsigned char *data, unsigned long datalen); int _libssh2_wincng_hash_final(_libssh2_wincng_hash_ctx *ctx, unsigned char *hash); int _libssh2_wincng_hash(unsigned char *data, unsigned long datalen, BCRYPT_ALG_HANDLE hAlg, unsigned char *hash, unsigned long hashlen); int _libssh2_wincng_hmac_final(_libssh2_wincng_hash_ctx *ctx, unsigned char *hash); void _libssh2_wincng_hmac_cleanup(_libssh2_wincng_hash_ctx *ctx); int _libssh2_wincng_key_sha1_verify(_libssh2_wincng_key_ctx *ctx, const unsigned char *sig, unsigned long sig_len, const unsigned char *m, unsigned long m_len, unsigned long flags); int _libssh2_wincng_rsa_new(libssh2_rsa_ctx **rsa, const unsigned char *edata, unsigned long elen, const unsigned char *ndata, unsigned long nlen, const unsigned char *ddata, unsigned long dlen, const unsigned char *pdata, unsigned long plen, const unsigned char *qdata, unsigned long qlen, const unsigned char *e1data, unsigned long e1len, const unsigned char *e2data, unsigned long e2len, const unsigned char *coeffdata, unsigned long coefflen); int _libssh2_wincng_rsa_new_private(libssh2_rsa_ctx **rsa, LIBSSH2_SESSION *session, const char *filename, const unsigned char *passphrase); int _libssh2_wincng_rsa_new_private_frommemory(libssh2_rsa_ctx **rsa, LIBSSH2_SESSION *session, const char *filedata, size_t filedata_len, unsigned const char *passphrase); int _libssh2_wincng_rsa_sha1_verify(libssh2_rsa_ctx *rsa, const unsigned char *sig, unsigned long sig_len, const unsigned char *m, unsigned long m_len); int _libssh2_wincng_rsa_sha1_sign(LIBSSH2_SESSION *session, libssh2_rsa_ctx *rsa, const unsigned char *hash, size_t hash_len, unsigned char **signature, size_t *signature_len); void _libssh2_wincng_rsa_free(libssh2_rsa_ctx *rsa); #if LIBSSH2_DSA int _libssh2_wincng_dsa_new(libssh2_dsa_ctx **dsa, const unsigned char *pdata, unsigned long plen, const unsigned char *qdata, unsigned long qlen, const unsigned char *gdata, unsigned long glen, const unsigned char *ydata, unsigned long ylen, const unsigned char *xdata, unsigned long xlen); int _libssh2_wincng_dsa_new_private(libssh2_dsa_ctx **dsa, LIBSSH2_SESSION *session, const char *filename, const unsigned char *passphrase); int _libssh2_wincng_dsa_new_private_frommemory(libssh2_dsa_ctx **dsa, LIBSSH2_SESSION *session, const char *filedata, size_t filedata_len, unsigned const char *passphrase); int _libssh2_wincng_dsa_sha1_verify(libssh2_dsa_ctx *dsa, const unsigned char *sig_fixed, const unsigned char *m, unsigned long m_len); int _libssh2_wincng_dsa_sha1_sign(libssh2_dsa_ctx *dsa, const unsigned char *hash, unsigned long hash_len, unsigned char *sig_fixed); void _libssh2_wincng_dsa_free(libssh2_dsa_ctx *dsa); #endif int _libssh2_wincng_pub_priv_keyfile(LIBSSH2_SESSION *session, unsigned char **method, size_t *method_len, unsigned char **pubkeydata, size_t *pubkeydata_len, const char *privatekey, const char *passphrase); int _libssh2_wincng_pub_priv_keyfilememory(LIBSSH2_SESSION *session, unsigned char **method, size_t *method_len, unsigned char **pubkeydata, size_t *pubkeydata_len, const char *privatekeydata, size_t privatekeydata_len, const char *passphrase); int _libssh2_wincng_cipher_init(_libssh2_cipher_ctx *ctx, _libssh2_cipher_type(type), unsigned char *iv, unsigned char *secret, int encrypt); int _libssh2_wincng_cipher_crypt(_libssh2_cipher_ctx *ctx, _libssh2_cipher_type(type), int encrypt, unsigned char *block, size_t blocklen); void _libssh2_wincng_cipher_dtor(_libssh2_cipher_ctx *ctx); _libssh2_bn * _libssh2_wincng_bignum_init(void); int _libssh2_wincng_bignum_rand(_libssh2_bn *rnd, int bits, int top, int bottom); int _libssh2_wincng_bignum_mod_exp(_libssh2_bn *r, _libssh2_bn *a, _libssh2_bn *p, _libssh2_bn *m, _libssh2_bn_ctx *bnctx); int _libssh2_wincng_bignum_set_word(_libssh2_bn *bn, unsigned long word); unsigned long _libssh2_wincng_bignum_bits(const _libssh2_bn *bn); void _libssh2_wincng_bignum_from_bin(_libssh2_bn *bn, unsigned long len, const unsigned char *bin); void _libssh2_wincng_bignum_to_bin(const _libssh2_bn *bn, unsigned char *bin); void _libssh2_wincng_bignum_free(_libssh2_bn *bn);
20,877
C++
.h
485
33.927835
78
0.602578
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,270
os400qc3.h
Studio3T_robomongo/src/third-party/libssh2-1.7.0/sources/src/os400qc3.h
/* * Copyright (C) 2015 Patrick Monnerat, D+H <patrick.monnerat@dh.com> * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifndef LIBSSH2_OS400QC3_H #define LIBSSH2_OS400QC3_H #include <stdlib.h> #include <string.h> #include <qc3cci.h> /* Redefine character/string literals as always EBCDIC. */ #undef Qc3_Alg_Token #define Qc3_Alg_Token "\xC1\xD3\xC7\xC4\xF0\xF1\xF0\xF0" /* ALGD0100 */ #undef Qc3_Alg_Block_Cipher #define Qc3_Alg_Block_Cipher "\xC1\xD3\xC7\xC4\xF0\xF2\xF0\xF0" /* ALGD0200 */ #undef Qc3_Alg_Block_CipherAuth #define Qc3_Alg_Block_CipherAuth \ "\xC1\xD3\xC7\xC4\xF0\xF2\xF1\xF0" /* ALGD0210 */ #undef Qc3_Alg_Stream_Cipher #define Qc3_Alg_Stream_Cipher \ "\xC1\xD3\xC7\xC4\xF0\xF3\xF0\xF0" /* ALGD0300 */ #undef Qc3_Alg_Public_Key #define Qc3_Alg_Public_Key "\xC1\xD3\xC7\xC4\xF0\xF4\xF0\xF0" /* ALGD0400 */ #undef Qc3_Alg_Hash #define Qc3_Alg_Hash "\xC1\xD3\xC7\xC4\xF0\xF5\xF0\xF0" /* ALGD0500 */ #undef Qc3_Data #define Qc3_Data "\xC4\xC1\xE3\xC1\xF0\xF1\xF0\xF0" /* DATA0100 */ #undef Qc3_Array #define Qc3_Array "\xC4\xC1\xE3\xC1\xF0\xF2\xF0\xF0" /* DATA0200 */ #undef Qc3_Key_Token #define Qc3_Key_Token "\xD2\xC5\xE8\xC4\xF0\xF1\xF0\xF0" /* KEYD0100 */ #undef Qc3_Key_Parms #define Qc3_Key_Parms "\xD2\xC5\xE8\xC4\xF0\xF2\xF0\xF0" /* KEYD0200 */ #undef Qc3_Key_KSLabel #define Qc3_Key_KSLabel "\xD2\xC5\xE8\xC4\xF0\xF4\xF0\xF0" /* KEYD0400 */ #undef Qc3_Key_PKCS5 #define Qc3_Key_PKCS5 "\xD2\xC5\xE8\xC4\xF0\xF5\xF0\xF0" /* KEYD0500 */ #undef Qc3_Key_PEMCert #define Qc3_Key_PEMCert "\xD2\xC5\xE8\xC4\xF0\xF6\xF0\xF0" /* KEYD0600 */ #undef Qc3_Key_CSLabel #define Qc3_Key_CSLabel "\xD2\xC5\xE8\xC4\xF0\xF7\xF0\xF0" /* KEYD0700 */ #undef Qc3_Key_CSDN #define Qc3_Key_CSDN "\xD2\xC5\xE8\xC4\xF0\xF8\xF0\xF0" /* KEYD0800 */ #undef Qc3_Key_AppID #define Qc3_Key_AppID "\xD2\xC5\xE8\xC4\xF0\xF9\xF0\xF0" /* KEYD0900 */ #undef Qc3_ECB #define Qc3_ECB '\xF0' /* '0' */ #undef Qc3_CBC #define Qc3_CBC '\xF1' /* '1' */ #undef Qc3_OFB #define Qc3_OFB '\xF2' /* '2' */ #undef Qc3_CFB1Bit #define Qc3_CFB1Bit '\xF3' /* '3' */ #undef Qc3_CFB8Bit #define Qc3_CFB8Bit '\xF4' /* '4' */ #undef Qc3_CFB64Bit #define Qc3_CFB64Bit '\xF5' /* '5' */ #undef Qc3_CUSP #define Qc3_CUSP '\xF6' /* '6' */ #undef Qc3_CTR #define Qc3_CTR '\xF7' /* '7' */ #undef Qc3_CCM #define Qc3_CCM '\xF8' /* '8' */ #undef Qc3_No_Pad #define Qc3_No_Pad '\xF0' /* '0' */ #undef Qc3_Pad_Char #define Qc3_Pad_Char '\xF1' /* '1' */ #undef Qc3_Pad_Counter #define Qc3_Pad_Counter '\xF2' /* '2' */ #undef Qc3_PKCS1_00 #define Qc3_PKCS1_00 '\xF0' /* '0' */ #undef Qc3_PKCS1_01 #define Qc3_PKCS1_01 '\xF1' /* '1' */ #undef Qc3_PKCS1_02 #define Qc3_PKCS1_02 '\xF2' /* '2' */ #undef Qc3_ISO9796 #define Qc3_ISO9796 '\xF3' /* '3' */ #undef Qc3_Zero_Pad #define Qc3_Zero_Pad '\xF4' /* '4' */ #undef Qc3_ANSI_X931 #define Qc3_ANSI_X931 '\xF5' /* '5' */ #undef Qc3_OAEP #define Qc3_OAEP '\xF6' /* '6' */ #undef Qc3_Bin_String #define Qc3_Bin_String '\xF0' /* '0' */ #undef Qc3_BER_String #define Qc3_BER_String '\xF1' /* '1' */ #undef Qc3_MK_Struct #define Qc3_MK_Struct '\xF3' /* '3' */ #undef Qc3_KSLabel_Struct #define Qc3_KSLabel_Struct '\xF4' /* '4' */ #undef Qc3_PKCS5_Struct #define Qc3_PKCS5_Struct '\xF5' /* '5' */ #undef Qc3_PEMCert_String #define Qc3_PEMCert_String '\xF6' /* '6' */ #undef Qc3_CSLabel_String #define Qc3_CSLabel_String '\xF7' /* '7' */ #undef Qc3_CSDN_String #define Qc3_CSDN_String '\xF8' /* '8' */ #undef Qc3_Clear #define Qc3_Clear '\xF0' /* '0' */ #undef Qc3_Encrypted #define Qc3_Encrypted '\xF1' /* '1' */ #undef Qc3_MK_Encrypted #define Qc3_MK_Encrypted '\xF2' /* '2' */ #undef Qc3_Any_CSP #define Qc3_Any_CSP '\xF0' /* '0' */ #undef Qc3_Sfw_CSP #define Qc3_Sfw_CSP '\xF1' /* '1' */ #undef Qc3_Hdw_CSP #define Qc3_Hdw_CSP '\xF2' /* '2' */ #undef Qc3_Continue #define Qc3_Continue '\xF0' /* '0' */ #undef Qc3_Final #define Qc3_Final '\xF1' /* '1' */ #undef Qc3_MK_New #define Qc3_MK_New '\xF0' /* '0' */ #undef Qc3_MK_Current #define Qc3_MK_Current '\xF1' /* '1' */ #undef Qc3_MK_Old #define Qc3_MK_Old '\xF2' /* '2' */ #undef Qc3_MK_Pending #define Qc3_MK_Pending '\xF3' /* '3' */ /* Define which features are supported. */ #define LIBSSH2_MD5 1 #define LIBSSH2_HMAC_RIPEMD 0 #define LIBSSH2_HMAC_SHA256 1 #define LIBSSH2_HMAC_SHA512 1 #define LIBSSH2_AES 1 #define LIBSSH2_AES_CTR 1 #define LIBSSH2_BLOWFISH 0 #define LIBSSH2_RC4 1 #define LIBSSH2_CAST 0 #define LIBSSH2_3DES 1 #define LIBSSH2_RSA 1 #define LIBSSH2_DSA 0 #define MD5_DIGEST_LENGTH 16 #define SHA_DIGEST_LENGTH 20 #define SHA256_DIGEST_LENGTH 32 #define SHA512_DIGEST_LENGTH 64 /******************************************************************* * * OS/400 QC3 crypto-library backend: global handles structures. * *******************************************************************/ /* HMAC & private key algorithms support structure. */ typedef struct _libssh2_os400qc3_crypto_ctx _libssh2_os400qc3_crypto_ctx; struct _libssh2_os400qc3_crypto_ctx { Qc3_Format_ALGD0100_T hash; /* Hash algorithm. */ Qc3_Format_KEYD0100_T key; /* Key. */ _libssh2_os400qc3_crypto_ctx * kek; /* Key encryption. */ }; typedef struct { /* Big number. */ unsigned char * bignum; /* Number bits, little-endian. */ unsigned int length; /* Length of bignum (# bytes). */ } _libssh2_bn; typedef struct { /* Algorithm description. */ char * fmt; /* Format of Qc3 structure. */ int algo; /* Algorithm identifier. */ unsigned char size; /* Block length. */ unsigned char mode; /* Block mode. */ int keylen; /* Key length. */ } _libssh2_os400qc3_cipher_t; /******************************************************************* * * OS/400 QC3 crypto-library backend: Define global types/codes. * *******************************************************************/ #define libssh2_crypto_init() #define libssh2_crypto_exit() #define libssh2_sha1_ctx Qc3_Format_ALGD0100_T #define libssh2_sha256_ctx Qc3_Format_ALGD0100_T #define libssh2_md5_ctx Qc3_Format_ALGD0100_T #define libssh2_hmac_ctx _libssh2_os400qc3_crypto_ctx #define _libssh2_cipher_ctx _libssh2_os400qc3_crypto_ctx #define libssh2_sha1_init(x) libssh2_os400qc3_hash_init(x, Qc3_SHA1) #define libssh2_sha1_update(ctx, data, len) \ libssh2_os400qc3_hash_update(&(ctx), data, len) #define libssh2_sha1_final(ctx, out) \ libssh2_os400qc3_hash_final(&(ctx), out) #define libssh2_sha256_init(x) libssh2_os400qc3_hash_init(x, Qc3_SHA256) #define libssh2_sha256_update(ctx, data, len) \ libssh2_os400qc3_hash_update(&(ctx), data, len) #define libssh2_sha256_final(ctx, out) \ libssh2_os400qc3_hash_final(&(ctx), out) #define libssh2_sha256(message, len, out) \ libssh2_os400qc3_hash(message, len, out, \ Qc3_SHA256) #define libssh2_md5_init(x) libssh2_os400qc3_hash_init(x, Qc3_MD5) #define libssh2_md5_update(ctx, data, len) \ libssh2_os400qc3_hash_update(&(ctx), data, len) #define libssh2_md5_final(ctx, out) \ libssh2_os400qc3_hash_final(&(ctx), out) #define libssh2_hmac_ctx_init(ctx) \ memset((char *) &(ctx), 0, \ sizeof(libssh2_hmac_ctx)) #define libssh2_hmac_md5_init(ctx, key, keylen) \ libssh2_os400qc3_hmac_init(ctx, Qc3_MD5, \ MD5_DIGEST_LENGTH, \ key, keylen) #define libssh2_hmac_sha1_init(ctx, key, keylen) \ libssh2_os400qc3_hmac_init(ctx, Qc3_SHA1, \ SHA_DIGEST_LENGTH, \ key, keylen) #define libssh2_hmac_sha256_init(ctx, key, keylen) \ libssh2_os400qc3_hmac_init(ctx, Qc3_SHA256, \ SHA256_DIGEST_LENGTH, \ key, keylen) #define libssh2_hmac_sha512_init(ctx, key, keylen) \ libssh2_os400qc3_hmac_init(ctx, Qc3_SHA512, \ SHA512_DIGEST_LENGTH, \ key, keylen) #define libssh2_hmac_update(ctx, data, datalen) \ libssh2_os400qc3_hmac_update(&(ctx), \ data, datalen) #define libssh2_hmac_final(ctx, data) \ libssh2_os400qc3_hmac_final(&(ctx), data) #define libssh2_hmac_cleanup(ctx) \ _libssh2_os400qc3_crypto_dtor(ctx) #define _libssh2_bn_ctx int /* Not used. */ #define _libssh2_bn_ctx_new() 0 #define _libssh2_bn_ctx_free(bnctx) ((void) 0) #define _libssh2_bn_init_from_bin() _libssh2_bn_init() #define _libssh2_bn_mod_exp(r, a, p, m, ctx) \ _libssh2_os400qc3_bn_mod_exp(r, a, p, m) #define _libssh2_bn_bytes(bn) ((bn)->length) #define _libssh2_cipher_type(name) _libssh2_os400qc3_cipher_t name #define _libssh2_cipher_aes128 {Qc3_Alg_Block_Cipher, Qc3_AES, 16, \ Qc3_CBC, 16} #define _libssh2_cipher_aes192 {Qc3_Alg_Block_Cipher, Qc3_AES, 24, \ Qc3_CBC, 24} #define _libssh2_cipher_aes256 {Qc3_Alg_Block_Cipher, Qc3_AES, 32, \ Qc3_CBC, 32} #define _libssh2_cipher_aes128ctr {Qc3_Alg_Block_Cipher, Qc3_AES, 16, \ Qc3_CTR, 16} #define _libssh2_cipher_aes192ctr {Qc3_Alg_Block_Cipher, Qc3_AES, 24, \ Qc3_CTR, 24} #define _libssh2_cipher_aes256ctr {Qc3_Alg_Block_Cipher, Qc3_AES, 32, \ Qc3_CTR, 32} #define _libssh2_cipher_3des {Qc3_Alg_Block_Cipher, Qc3_TDES, 0, \ Qc3_CBC, 24} #define _libssh2_cipher_arcfour {Qc3_Alg_Stream_Cipher, Qc3_RC4, 0, 0, 16} #define _libssh2_cipher_dtor(ctx) _libssh2_os400qc3_crypto_dtor(ctx) #define libssh2_rsa_ctx _libssh2_os400qc3_crypto_ctx #define _libssh2_rsa_free(ctx) (_libssh2_os400qc3_crypto_dtor(ctx), \ free((char *) ctx)) #define libssh2_prepare_iovec(vec, len) memset((char *) (vec), 0, \ (len) * sizeof(struct iovec)) #define _libssh2_rsa_sha1_signv(session, sig, siglen, count, vector, ctx) \ _libssh2_os400qc3_rsa_sha1_signv(session, sig, siglen, \ count, vector, ctx) /******************************************************************* * * OS/400 QC3 crypto-library backend: Support procedure prototypes. * *******************************************************************/ extern _libssh2_bn * _libssh2_bn_init(void); extern void _libssh2_bn_free(_libssh2_bn *bn); extern unsigned long _libssh2_bn_bits(_libssh2_bn *bn); extern int _libssh2_bn_from_bin(_libssh2_bn *bn, int len, const unsigned char *v); extern int _libssh2_bn_set_word(_libssh2_bn *bn, unsigned long val); extern int _libssh2_bn_to_bin(_libssh2_bn *bn, unsigned char *val); extern void _libssh2_random(unsigned char *buf, int len); extern int _libssh2_bn_rand(_libssh2_bn *bn, int bits, int top, int bottom); extern int _libssh2_os400qc3_bn_mod_exp(_libssh2_bn *r, _libssh2_bn *a, _libssh2_bn *p, _libssh2_bn *m); extern void _libssh2_os400qc3_crypto_dtor(_libssh2_os400qc3_crypto_ctx *x); extern int libssh2_os400qc3_hash_init(Qc3_Format_ALGD0100_T *x, unsigned int algo); extern void libssh2_os400qc3_hash_update(Qc3_Format_ALGD0100_T *ctx, unsigned char *data, int len); extern void libssh2_os400qc3_hash_final(Qc3_Format_ALGD0100_T *ctx, unsigned char *out); extern int libssh2_os400qc3_hash(const unsigned char *message, unsigned long len, unsigned char *out, unsigned int algo); extern void libssh2_os400qc3_hmac_init(_libssh2_os400qc3_crypto_ctx *x, int algo, size_t minkeylen, void *key, int keylen); extern void libssh2_os400qc3_hmac_update(_libssh2_os400qc3_crypto_ctx *ctx, const unsigned char *data, int len); extern void libssh2_os400qc3_hmac_final(_libssh2_os400qc3_crypto_ctx *ctx, unsigned char *out); extern int _libssh2_os400qc3_rsa_sha1_signv(LIBSSH2_SESSION *session, unsigned char **signature, size_t *signature_len, int veccount, const struct iovec vector[], libssh2_rsa_ctx *ctx); #endif /* vim: set expandtab ts=4 sw=4: */
16,859
C++
.h
326
43.159509
80
0.525908
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,271
misc.h
Studio3T_robomongo/src/third-party/libssh2-1.7.0/sources/src/misc.h
#ifndef __LIBSSH2_MISC_H #define __LIBSSH2_MISC_H /* Copyright (c) 2009-2014 by Daniel Stenberg * * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ struct list_head { struct list_node *last; struct list_node *first; }; struct list_node { struct list_node *next; struct list_node *prev; struct list_head *head; }; int _libssh2_error_flags(LIBSSH2_SESSION* session, int errcode, const char* errmsg, int errflags); int _libssh2_error(LIBSSH2_SESSION* session, int errcode, const char* errmsg); void _libssh2_list_init(struct list_head *head); /* add a node last in the list */ void _libssh2_list_add(struct list_head *head, struct list_node *entry); /* return the "first" node in the list this head points to */ void *_libssh2_list_first(struct list_head *head); /* return the next node in the list */ void *_libssh2_list_next(struct list_node *node); /* return the prev node in the list */ void *_libssh2_list_prev(struct list_node *node); /* remove this node from the list */ void _libssh2_list_remove(struct list_node *entry); size_t _libssh2_base64_encode(struct _LIBSSH2_SESSION *session, const char *inp, size_t insize, char **outptr); unsigned int _libssh2_ntohu32(const unsigned char *buf); libssh2_uint64_t _libssh2_ntohu64(const unsigned char *buf); void _libssh2_htonu32(unsigned char *buf, uint32_t val); void _libssh2_store_u32(unsigned char **buf, uint32_t value); void _libssh2_store_str(unsigned char **buf, const char *str, size_t len); void *_libssh2_calloc(LIBSSH2_SESSION* session, size_t size); #if defined(LIBSSH2_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__) /* provide a private one */ #undef HAVE_GETTIMEOFDAY int __cdecl _libssh2_gettimeofday(struct timeval *tp, void *tzp); #define HAVE_LIBSSH2_GETTIMEOFDAY #define LIBSSH2_GETTIMEOFDAY_WIN32 /* enable the win32 implementation */ #else #ifdef HAVE_GETTIMEOFDAY #define _libssh2_gettimeofday(x,y) gettimeofday(x,y) #define HAVE_LIBSSH2_GETTIMEOFDAY #endif #endif #endif /* _LIBSSH2_MISC_H */
3,582
C++
.h
83
40.686747
98
0.749283
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,272
sftp.h
Studio3T_robomongo/src/third-party/libssh2-1.7.0/sources/src/sftp.h
#ifndef _LIBSSH2_SFTP_H #define _LIBSSH2_SFTP_H /* * Copyright (C) 2010 - 2012 by Daniel Stenberg * Author: Daniel Stenberg <daniel@haxx.se> * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * */ /* * MAX_SFTP_OUTGOING_SIZE MUST not be larger than 32500 or so. This is the * amount of data sent in each FXP_WRITE packet */ #define MAX_SFTP_OUTGOING_SIZE 30000 /* MAX_SFTP_READ_SIZE is how much data is asked for at max in each FXP_READ * packets. */ #define MAX_SFTP_READ_SIZE 30000 struct sftp_pipeline_chunk { struct list_node node; libssh2_uint64_t offset; /* READ: offset at which to start reading WRITE: not used */ size_t len; /* WRITE: size of the data to write READ: how many bytes that was asked for */ size_t sent; ssize_t lefttosend; /* if 0, the entire packet has been sent off */ uint32_t request_id; unsigned char packet[1]; /* data */ }; struct sftp_zombie_requests { struct list_node node; uint32_t request_id; }; #ifndef MIN #define MIN(x,y) ((x)<(y)?(x):(y)) #endif struct _LIBSSH2_SFTP_PACKET { struct list_node node; /* linked list header */ uint32_t request_id; unsigned char *data; size_t data_len; /* payload size */ }; typedef struct _LIBSSH2_SFTP_PACKET LIBSSH2_SFTP_PACKET; #define SFTP_HANDLE_MAXLEN 256 /* according to spec! */ struct _LIBSSH2_SFTP_HANDLE { struct list_node node; LIBSSH2_SFTP *sftp; char handle[SFTP_HANDLE_MAXLEN]; size_t handle_len; enum { LIBSSH2_SFTP_HANDLE_FILE, LIBSSH2_SFTP_HANDLE_DIR } handle_type; union _libssh2_sftp_handle_data { struct _libssh2_sftp_handle_file_data { libssh2_uint64_t offset; libssh2_uint64_t offset_sent; size_t acked; /* container for acked data that hasn't been returned to caller yet, used for sftp_write */ /* 'data' is used by sftp_read() and is allocated data that has been received already from the server but wasn't returned to the caller yet. It is of size 'data_len' and 'data_left is the number of bytes not yet returned, counted from the end of the buffer. */ unsigned char *data; size_t data_len; size_t data_left; char eof; /* we have read to the end */ } file; struct _libssh2_sftp_handle_dir_data { uint32_t names_left; void *names_packet; char *next_name; } dir; } u; /* State variables used in libssh2_sftp_close_handle() */ libssh2_nonblocking_states close_state; uint32_t close_request_id; unsigned char *close_packet; /* list of outstanding packets sent to server */ struct list_head packet_list; }; struct _LIBSSH2_SFTP { LIBSSH2_CHANNEL *channel; uint32_t request_id, version; struct list_head packets; /* List of FXP_READ responses to ignore because EOF already received. */ struct list_head zombie_requests; /* a list of _LIBSSH2_SFTP_HANDLE structs */ struct list_head sftp_handles; uint32_t last_errno; /* Holder for partial packet, use in libssh2_sftp_packet_read() */ unsigned char partial_size[4]; /* buffer for size field */ size_t partial_size_len; /* size field length */ unsigned char *partial_packet; /* The data */ uint32_t partial_len; /* Desired number of bytes */ size_t partial_received; /* Bytes received so far */ /* Time that libssh2_sftp_packet_requirev() started reading */ time_t requirev_start; /* State variables used in libssh2_sftp_open_ex() */ libssh2_nonblocking_states open_state; unsigned char *open_packet; uint32_t open_packet_len; /* 32 bit on the wire */ size_t open_packet_sent; uint32_t open_request_id; /* State variable used in sftp_read() */ libssh2_nonblocking_states read_state; /* State variable used in sftp_packet_read() */ libssh2_nonblocking_states packet_state; /* State variable used in sftp_write() */ libssh2_nonblocking_states write_state; /* State variables used in sftp_fsync() */ libssh2_nonblocking_states fsync_state; unsigned char *fsync_packet; uint32_t fsync_request_id; /* State variables used in libssh2_sftp_readdir() */ libssh2_nonblocking_states readdir_state; unsigned char *readdir_packet; uint32_t readdir_request_id; /* State variables used in libssh2_sftp_fstat_ex() */ libssh2_nonblocking_states fstat_state; unsigned char *fstat_packet; uint32_t fstat_request_id; /* State variables used in libssh2_sftp_unlink_ex() */ libssh2_nonblocking_states unlink_state; unsigned char *unlink_packet; uint32_t unlink_request_id; /* State variables used in libssh2_sftp_rename_ex() */ libssh2_nonblocking_states rename_state; unsigned char *rename_packet; unsigned char *rename_s; uint32_t rename_request_id; /* State variables used in libssh2_sftp_fstatvfs() */ libssh2_nonblocking_states fstatvfs_state; unsigned char *fstatvfs_packet; uint32_t fstatvfs_request_id; /* State variables used in libssh2_sftp_statvfs() */ libssh2_nonblocking_states statvfs_state; unsigned char *statvfs_packet; uint32_t statvfs_request_id; /* State variables used in libssh2_sftp_mkdir() */ libssh2_nonblocking_states mkdir_state; unsigned char *mkdir_packet; uint32_t mkdir_request_id; /* State variables used in libssh2_sftp_rmdir() */ libssh2_nonblocking_states rmdir_state; unsigned char *rmdir_packet; uint32_t rmdir_request_id; /* State variables used in libssh2_sftp_stat() */ libssh2_nonblocking_states stat_state; unsigned char *stat_packet; uint32_t stat_request_id; /* State variables used in libssh2_sftp_symlink() */ libssh2_nonblocking_states symlink_state; unsigned char *symlink_packet; uint32_t symlink_request_id; }; #endif
7,653
C++
.h
195
34.020513
77
0.686624
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,273
libssh2_priv.h
Studio3T_robomongo/src/third-party/libssh2-1.7.0/sources/src/libssh2_priv.h
/* Copyright (c) 2004-2008, 2010, Sara Golemon <sarag@libssh2.org> * Copyright (c) 2009-2014 by Daniel Stenberg * Copyright (c) 2010 Simon Josefsson * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifndef LIBSSH2_PRIV_H #define LIBSSH2_PRIV_H 1 #define LIBSSH2_LIBRARY #include "libssh2_config.h" #ifdef HAVE_WINDOWS_H #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #undef WIN32_LEAN_AND_MEAN #endif #ifdef HAVE_WS2TCPIP_H #include <ws2tcpip.h> #endif #include <stdio.h> #include <time.h> /* The following CPP block should really only be in session.c and packet.c. However, AIX have #define's for 'events' and 'revents' and we are using those names in libssh2.h, so we need to include the AIX headers first, to make sure all code is compiled with consistent names of these fields. While arguable the best would to change libssh2.h to use other names, that would break backwards compatibility. For more information, see: https://www.mail-archive.com/libssh2-devel%40lists.sourceforge.net/msg00003.html https://www.mail-archive.com/libssh2-devel%40lists.sourceforge.net/msg00224.html */ #ifdef HAVE_POLL # include <sys/poll.h> #else # if defined(HAVE_SELECT) && !defined(WIN32) # ifdef HAVE_SYS_SELECT_H # include <sys/select.h> # else # include <sys/time.h> # include <sys/types.h> # endif # endif #endif /* Needed for struct iovec on some platforms */ #ifdef HAVE_SYS_UIO_H #include <sys/uio.h> #endif #ifdef HAVE_SYS_SOCKET_H # include <sys/socket.h> #endif #ifdef HAVE_SYS_IOCTL_H # include <sys/ioctl.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include "libssh2.h" #include "libssh2_publickey.h" #include "libssh2_sftp.h" #include "misc.h" /* for the linked list stuff */ #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #ifdef _MSC_VER /* "inline" keyword is valid only with C++ engine! */ #define inline __inline #endif /* Provide iovec / writev on WIN32 platform. */ #ifdef WIN32 struct iovec { size_t iov_len; void * iov_base; }; static inline int writev(int sock, struct iovec *iov, int nvecs) { DWORD ret; if (WSASend(sock, (LPWSABUF)iov, nvecs, &ret, 0, NULL, NULL) == 0) { return ret; } return -1; } #endif /* WIN32 */ #ifdef __OS400__ /* Force parameter type. */ #define send(s, b, l, f) send((s), (unsigned char *) (b), (l), (f)) #endif #include "crypto.h" #ifdef HAVE_WINSOCK2_H #include <winsock2.h> #include <ws2tcpip.h> #endif /* RFC4253 section 6.1 Maximum Packet Length says: * * "All implementations MUST be able to process packets with * uncompressed payload length of 32768 bytes or less and * total packet size of 35000 bytes or less (including length, * padding length, payload, padding, and MAC.)." */ #define MAX_SSH_PACKET_LEN 35000 #define MAX_SHA_DIGEST_LEN SHA256_DIGEST_LENGTH #define LIBSSH2_ALLOC(session, count) \ session->alloc((count), &(session)->abstract) #define LIBSSH2_CALLOC(session, count) _libssh2_calloc(session, count) #define LIBSSH2_REALLOC(session, ptr, count) \ ((ptr) ? session->realloc((ptr), (count), &(session)->abstract) : \ session->alloc((count), &(session)->abstract)) #define LIBSSH2_FREE(session, ptr) \ session->free((ptr), &(session)->abstract) #define LIBSSH2_IGNORE(session, data, datalen) \ session->ssh_msg_ignore((session), (data), (datalen), &(session)->abstract) #define LIBSSH2_DEBUG(session, always_display, message, message_len, \ language, language_len) \ session->ssh_msg_debug((session), (always_display), (message), \ (message_len), (language), (language_len), \ &(session)->abstract) #define LIBSSH2_DISCONNECT(session, reason, message, message_len, \ language, language_len) \ session->ssh_msg_disconnect((session), (reason), (message), \ (message_len), (language), (language_len), \ &(session)->abstract) #define LIBSSH2_MACERROR(session, data, datalen) \ session->macerror((session), (data), (datalen), &(session)->abstract) #define LIBSSH2_X11_OPEN(channel, shost, sport) \ channel->session->x11(((channel)->session), (channel), \ (shost), (sport), (&(channel)->session->abstract)) #define LIBSSH2_CHANNEL_CLOSE(session, channel) \ channel->close_cb((session), &(session)->abstract, \ (channel), &(channel)->abstract) #define LIBSSH2_SEND_FD(session, fd, buffer, length, flags) \ (session->send)(fd, buffer, length, flags, &session->abstract) #define LIBSSH2_RECV_FD(session, fd, buffer, length, flags) \ (session->recv)(fd, buffer, length, flags, &session->abstract) #define LIBSSH2_SEND(session, buffer, length, flags) \ LIBSSH2_SEND_FD(session, session->socket_fd, buffer, length, flags) #define LIBSSH2_RECV(session, buffer, length, flags) \ LIBSSH2_RECV_FD(session, session->socket_fd, buffer, length, flags) typedef struct _LIBSSH2_KEX_METHOD LIBSSH2_KEX_METHOD; typedef struct _LIBSSH2_HOSTKEY_METHOD LIBSSH2_HOSTKEY_METHOD; typedef struct _LIBSSH2_CRYPT_METHOD LIBSSH2_CRYPT_METHOD; typedef struct _LIBSSH2_COMP_METHOD LIBSSH2_COMP_METHOD; typedef struct _LIBSSH2_PACKET LIBSSH2_PACKET; typedef enum { libssh2_NB_state_idle = 0, libssh2_NB_state_allocated, libssh2_NB_state_created, libssh2_NB_state_sent, libssh2_NB_state_sent1, libssh2_NB_state_sent2, libssh2_NB_state_sent3, libssh2_NB_state_sent4, libssh2_NB_state_sent5, libssh2_NB_state_sent6, libssh2_NB_state_sent7, libssh2_NB_state_jump1, libssh2_NB_state_jump2, libssh2_NB_state_jump3, libssh2_NB_state_jump4, libssh2_NB_state_jump5, libssh2_NB_state_end } libssh2_nonblocking_states; typedef struct packet_require_state_t { libssh2_nonblocking_states state; time_t start; } packet_require_state_t; typedef struct packet_requirev_state_t { time_t start; } packet_requirev_state_t; typedef struct kmdhgGPshakex_state_t { libssh2_nonblocking_states state; unsigned char *e_packet; unsigned char *s_packet; unsigned char *tmp; unsigned char h_sig_comp[MAX_SHA_DIGEST_LEN]; unsigned char c; size_t e_packet_len; size_t s_packet_len; size_t tmp_len; _libssh2_bn_ctx *ctx; _libssh2_bn *x; _libssh2_bn *e; _libssh2_bn *f; _libssh2_bn *k; unsigned char *s; unsigned char *f_value; unsigned char *k_value; unsigned char *h_sig; size_t f_value_len; size_t k_value_len; size_t h_sig_len; void *exchange_hash; packet_require_state_t req_state; libssh2_nonblocking_states burn_state; } kmdhgGPshakex_state_t; typedef struct key_exchange_state_low_t { libssh2_nonblocking_states state; packet_require_state_t req_state; kmdhgGPshakex_state_t exchange_state; _libssh2_bn *p; /* SSH2 defined value (p_value) */ _libssh2_bn *g; /* SSH2 defined value (2) */ unsigned char request[13]; unsigned char *data; size_t request_len; size_t data_len; } key_exchange_state_low_t; typedef struct key_exchange_state_t { libssh2_nonblocking_states state; packet_require_state_t req_state; key_exchange_state_low_t key_state_low; unsigned char *data; size_t data_len; unsigned char *oldlocal; size_t oldlocal_len; } key_exchange_state_t; #define FwdNotReq "Forward not requested" typedef struct packet_queue_listener_state_t { libssh2_nonblocking_states state; unsigned char packet[17 + (sizeof(FwdNotReq) - 1)]; unsigned char *host; unsigned char *shost; uint32_t sender_channel; uint32_t initial_window_size; uint32_t packet_size; uint32_t port; uint32_t sport; uint32_t host_len; uint32_t shost_len; LIBSSH2_CHANNEL *channel; } packet_queue_listener_state_t; #define X11FwdUnAvil "X11 Forward Unavailable" typedef struct packet_x11_open_state_t { libssh2_nonblocking_states state; unsigned char packet[17 + (sizeof(X11FwdUnAvil) - 1)]; unsigned char *shost; uint32_t sender_channel; uint32_t initial_window_size; uint32_t packet_size; uint32_t sport; uint32_t shost_len; LIBSSH2_CHANNEL *channel; } packet_x11_open_state_t; struct _LIBSSH2_PACKET { struct list_node node; /* linked list header */ /* the raw unencrypted payload */ unsigned char *data; size_t data_len; /* Where to start reading data from, * used for channel data that's been partially consumed */ size_t data_head; }; typedef struct _libssh2_channel_data { /* Identifier */ uint32_t id; /* Limits and restrictions */ uint32_t window_size_initial, window_size, packet_size; /* Set to 1 when CHANNEL_CLOSE / CHANNEL_EOF sent/received */ char close, eof, extended_data_ignore_mode; } libssh2_channel_data; struct _LIBSSH2_CHANNEL { struct list_node node; unsigned char *channel_type; unsigned channel_type_len; /* channel's program exit status */ int exit_status; /* channel's program exit signal (without the SIG prefix) */ char *exit_signal; libssh2_channel_data local, remote; /* Amount of bytes to be refunded to receive window (but not yet sent) */ uint32_t adjust_queue; /* Data immediately available for reading */ uint32_t read_avail; LIBSSH2_SESSION *session; void *abstract; LIBSSH2_CHANNEL_CLOSE_FUNC((*close_cb)); /* State variables used in libssh2_channel_setenv_ex() */ libssh2_nonblocking_states setenv_state; unsigned char *setenv_packet; size_t setenv_packet_len; unsigned char setenv_local_channel[4]; packet_requirev_state_t setenv_packet_requirev_state; /* State variables used in libssh2_channel_request_pty_ex() libssh2_channel_request_pty_size_ex() */ libssh2_nonblocking_states reqPTY_state; unsigned char reqPTY_packet[41 + 256]; size_t reqPTY_packet_len; unsigned char reqPTY_local_channel[4]; packet_requirev_state_t reqPTY_packet_requirev_state; /* State variables used in libssh2_channel_x11_req_ex() */ libssh2_nonblocking_states reqX11_state; unsigned char *reqX11_packet; size_t reqX11_packet_len; unsigned char reqX11_local_channel[4]; packet_requirev_state_t reqX11_packet_requirev_state; /* State variables used in libssh2_channel_process_startup() */ libssh2_nonblocking_states process_state; unsigned char *process_packet; size_t process_packet_len; unsigned char process_local_channel[4]; packet_requirev_state_t process_packet_requirev_state; /* State variables used in libssh2_channel_flush_ex() */ libssh2_nonblocking_states flush_state; size_t flush_refund_bytes; size_t flush_flush_bytes; /* State variables used in libssh2_channel_receive_window_adjust() */ libssh2_nonblocking_states adjust_state; unsigned char adjust_adjust[9]; /* packet_type(1) + channel(4) + adjustment(4) */ /* State variables used in libssh2_channel_read_ex() */ libssh2_nonblocking_states read_state; uint32_t read_local_id; /* State variables used in libssh2_channel_write_ex() */ libssh2_nonblocking_states write_state; unsigned char write_packet[13]; size_t write_packet_len; size_t write_bufwrite; /* State variables used in libssh2_channel_close() */ libssh2_nonblocking_states close_state; unsigned char close_packet[5]; /* State variables used in libssh2_channel_wait_closedeof() */ libssh2_nonblocking_states wait_eof_state; /* State variables used in libssh2_channel_wait_closed() */ libssh2_nonblocking_states wait_closed_state; /* State variables used in libssh2_channel_free() */ libssh2_nonblocking_states free_state; /* State variables used in libssh2_channel_handle_extended_data2() */ libssh2_nonblocking_states extData2_state; }; struct _LIBSSH2_LISTENER { struct list_node node; /* linked list header */ LIBSSH2_SESSION *session; char *host; int port; /* a list of CHANNELs for this listener */ struct list_head queue; int queue_size; int queue_maxsize; /* State variables used in libssh2_channel_forward_cancel() */ libssh2_nonblocking_states chanFwdCncl_state; unsigned char *chanFwdCncl_data; size_t chanFwdCncl_data_len; }; typedef struct _libssh2_endpoint_data { unsigned char *banner; unsigned char *kexinit; size_t kexinit_len; const LIBSSH2_CRYPT_METHOD *crypt; void *crypt_abstract; const struct _LIBSSH2_MAC_METHOD *mac; uint32_t seqno; void *mac_abstract; const LIBSSH2_COMP_METHOD *comp; void *comp_abstract; /* Method Preferences -- NULL yields "load order" */ char *crypt_prefs; char *mac_prefs; char *comp_prefs; char *lang_prefs; } libssh2_endpoint_data; #define PACKETBUFSIZE (1024*16) struct transportpacket { /* ------------- for incoming data --------------- */ unsigned char buf[PACKETBUFSIZE]; unsigned char init[5]; /* first 5 bytes of the incoming data stream, still encrypted */ size_t writeidx; /* at what array index we do the next write into the buffer */ size_t readidx; /* at what array index we do the next read from the buffer */ uint32_t packet_length; /* the most recent packet_length as read from the network data */ uint8_t padding_length; /* the most recent padding_length as read from the network data */ size_t data_num; /* How much of the total package that has been read so far. */ size_t total_num; /* How much a total package is supposed to be, in number of bytes. A full package is packet_length + padding_length + 4 + mac_length. */ unsigned char *payload; /* this is a pointer to a LIBSSH2_ALLOC() area to which we write decrypted data */ unsigned char *wptr; /* write pointer into the payload to where we are currently writing decrypted data */ /* ------------- for outgoing data --------------- */ unsigned char outbuf[MAX_SSH_PACKET_LEN]; /* area for the outgoing data */ int ototal_num; /* size of outbuf in number of bytes */ const unsigned char *odata; /* original pointer to the data */ size_t olen; /* original size of the data we stored in outbuf */ size_t osent; /* number of bytes already sent */ }; struct _LIBSSH2_PUBLICKEY { LIBSSH2_CHANNEL *channel; uint32_t version; /* State variables used in libssh2_publickey_packet_receive() */ libssh2_nonblocking_states receive_state; unsigned char *receive_packet; size_t receive_packet_len; /* State variables used in libssh2_publickey_add_ex() */ libssh2_nonblocking_states add_state; unsigned char *add_packet; unsigned char *add_s; /* State variables used in libssh2_publickey_remove_ex() */ libssh2_nonblocking_states remove_state; unsigned char *remove_packet; unsigned char *remove_s; /* State variables used in libssh2_publickey_list_fetch() */ libssh2_nonblocking_states listFetch_state; unsigned char *listFetch_s; unsigned char listFetch_buffer[12]; unsigned char *listFetch_data; size_t listFetch_data_len; }; #define LIBSSH2_SCP_RESPONSE_BUFLEN 256 struct flags { int sigpipe; /* LIBSSH2_FLAG_SIGPIPE */ int compress; /* LIBSSH2_FLAG_COMPRESS */ }; struct _LIBSSH2_SESSION { /* Memory management callbacks */ void *abstract; LIBSSH2_ALLOC_FUNC((*alloc)); LIBSSH2_REALLOC_FUNC((*realloc)); LIBSSH2_FREE_FUNC((*free)); /* Other callbacks */ LIBSSH2_IGNORE_FUNC((*ssh_msg_ignore)); LIBSSH2_DEBUG_FUNC((*ssh_msg_debug)); LIBSSH2_DISCONNECT_FUNC((*ssh_msg_disconnect)); LIBSSH2_MACERROR_FUNC((*macerror)); LIBSSH2_X11_OPEN_FUNC((*x11)); LIBSSH2_SEND_FUNC((*send)); LIBSSH2_RECV_FUNC((*recv)); /* Method preferences -- NULL yields "load order" */ char *kex_prefs; char *hostkey_prefs; int state; /* Flag options */ struct flags flag; /* Agreed Key Exchange Method */ const LIBSSH2_KEX_METHOD *kex; unsigned int burn_optimistic_kexinit:1; unsigned char *session_id; uint32_t session_id_len; /* this is set to TRUE if a blocking API behavior is requested */ int api_block_mode; /* Timeout used when blocking API behavior is active */ long api_timeout; /* Server's public key */ const LIBSSH2_HOSTKEY_METHOD *hostkey; void *server_hostkey_abstract; /* Either set with libssh2_session_hostkey() (for server mode) * Or read from server in (eg) KEXDH_INIT (for client mode) */ unsigned char *server_hostkey; uint32_t server_hostkey_len; #if LIBSSH2_MD5 unsigned char server_hostkey_md5[MD5_DIGEST_LENGTH]; int server_hostkey_md5_valid; #endif /* ! LIBSSH2_MD5 */ unsigned char server_hostkey_sha1[SHA_DIGEST_LENGTH]; int server_hostkey_sha1_valid; /* (remote as source of data -- packet_read ) */ libssh2_endpoint_data remote; /* (local as source of data -- packet_write ) */ libssh2_endpoint_data local; /* Inbound Data linked list -- Sometimes the packet that comes in isn't the packet we're ready for */ struct list_head packets; /* Active connection channels */ struct list_head channels; uint32_t next_channel; struct list_head listeners; /* list of LIBSSH2_LISTENER structs */ /* Actual I/O socket */ libssh2_socket_t socket_fd; int socket_state; int socket_block_directions; int socket_prev_blockstate; /* stores the state of the socket blockiness when libssh2_session_startup() is called */ /* Error tracking */ const char *err_msg; int err_code; int err_flags; /* struct members for packet-level reading */ struct transportpacket packet; #ifdef LIBSSH2DEBUG int showmask; /* what debug/trace messages to display */ libssh2_trace_handler_func tracehandler; /* callback to display trace messages */ void* tracehandler_context; /* context for the trace handler */ #endif /* State variables used in libssh2_banner_send() */ libssh2_nonblocking_states banner_TxRx_state; char banner_TxRx_banner[256]; ssize_t banner_TxRx_total_send; /* State variables used in libssh2_kexinit() */ libssh2_nonblocking_states kexinit_state; unsigned char *kexinit_data; size_t kexinit_data_len; /* State variables used in libssh2_session_startup() */ libssh2_nonblocking_states startup_state; unsigned char *startup_data; size_t startup_data_len; unsigned char startup_service[sizeof("ssh-userauth") + 5 - 1]; size_t startup_service_length; packet_require_state_t startup_req_state; key_exchange_state_t startup_key_state; /* State variables used in libssh2_session_free() */ libssh2_nonblocking_states free_state; /* State variables used in libssh2_session_disconnect_ex() */ libssh2_nonblocking_states disconnect_state; unsigned char disconnect_data[256 + 13]; size_t disconnect_data_len; /* State variables used in libssh2_packet_read() */ libssh2_nonblocking_states readPack_state; int readPack_encrypted; /* State variables used in libssh2_userauth_list() */ libssh2_nonblocking_states userauth_list_state; unsigned char *userauth_list_data; size_t userauth_list_data_len; packet_requirev_state_t userauth_list_packet_requirev_state; /* State variables used in libssh2_userauth_password_ex() */ libssh2_nonblocking_states userauth_pswd_state; unsigned char *userauth_pswd_data; unsigned char userauth_pswd_data0; size_t userauth_pswd_data_len; char *userauth_pswd_newpw; int userauth_pswd_newpw_len; packet_requirev_state_t userauth_pswd_packet_requirev_state; /* State variables used in libssh2_userauth_hostbased_fromfile_ex() */ libssh2_nonblocking_states userauth_host_state; unsigned char *userauth_host_data; size_t userauth_host_data_len; unsigned char *userauth_host_packet; size_t userauth_host_packet_len; unsigned char *userauth_host_method; size_t userauth_host_method_len; unsigned char *userauth_host_s; packet_requirev_state_t userauth_host_packet_requirev_state; /* State variables used in libssh2_userauth_publickey_fromfile_ex() */ libssh2_nonblocking_states userauth_pblc_state; unsigned char *userauth_pblc_data; size_t userauth_pblc_data_len; unsigned char *userauth_pblc_packet; size_t userauth_pblc_packet_len; unsigned char *userauth_pblc_method; size_t userauth_pblc_method_len; unsigned char *userauth_pblc_s; unsigned char *userauth_pblc_b; packet_requirev_state_t userauth_pblc_packet_requirev_state; /* State variables used in libssh2_userauth_keyboard_interactive_ex() */ libssh2_nonblocking_states userauth_kybd_state; unsigned char *userauth_kybd_data; size_t userauth_kybd_data_len; unsigned char *userauth_kybd_packet; size_t userauth_kybd_packet_len; unsigned int userauth_kybd_auth_name_len; char *userauth_kybd_auth_name; unsigned userauth_kybd_auth_instruction_len; char *userauth_kybd_auth_instruction; unsigned int userauth_kybd_num_prompts; int userauth_kybd_auth_failure; LIBSSH2_USERAUTH_KBDINT_PROMPT *userauth_kybd_prompts; LIBSSH2_USERAUTH_KBDINT_RESPONSE *userauth_kybd_responses; packet_requirev_state_t userauth_kybd_packet_requirev_state; /* State variables used in libssh2_channel_open_ex() */ libssh2_nonblocking_states open_state; packet_requirev_state_t open_packet_requirev_state; LIBSSH2_CHANNEL *open_channel; unsigned char *open_packet; size_t open_packet_len; unsigned char *open_data; size_t open_data_len; uint32_t open_local_channel; /* State variables used in libssh2_channel_direct_tcpip_ex() */ libssh2_nonblocking_states direct_state; unsigned char *direct_message; size_t direct_host_len; size_t direct_shost_len; size_t direct_message_len; /* State variables used in libssh2_channel_forward_listen_ex() */ libssh2_nonblocking_states fwdLstn_state; unsigned char *fwdLstn_packet; uint32_t fwdLstn_host_len; uint32_t fwdLstn_packet_len; packet_requirev_state_t fwdLstn_packet_requirev_state; /* State variables used in libssh2_publickey_init() */ libssh2_nonblocking_states pkeyInit_state; LIBSSH2_PUBLICKEY *pkeyInit_pkey; LIBSSH2_CHANNEL *pkeyInit_channel; unsigned char *pkeyInit_data; size_t pkeyInit_data_len; /* 19 = packet_len(4) + version_len(4) + "version"(7) + version_num(4) */ unsigned char pkeyInit_buffer[19]; size_t pkeyInit_buffer_sent; /* how much of buffer that has been sent */ /* State variables used in libssh2_packet_add() */ libssh2_nonblocking_states packAdd_state; LIBSSH2_CHANNEL *packAdd_channelp; /* keeper of the channel during EAGAIN states */ packet_queue_listener_state_t packAdd_Qlstn_state; packet_x11_open_state_t packAdd_x11open_state; /* State variables used in fullpacket() */ libssh2_nonblocking_states fullpacket_state; int fullpacket_macstate; size_t fullpacket_payload_len; int fullpacket_packet_type; /* State variables used in libssh2_sftp_init() */ libssh2_nonblocking_states sftpInit_state; LIBSSH2_SFTP *sftpInit_sftp; LIBSSH2_CHANNEL *sftpInit_channel; unsigned char sftpInit_buffer[9]; /* sftp_header(5){excludes request_id} + version_id(4) */ int sftpInit_sent; /* number of bytes from the buffer that have been sent */ /* State variables used in libssh2_scp_recv() / libssh_scp_recv2() */ libssh2_nonblocking_states scpRecv_state; unsigned char *scpRecv_command; size_t scpRecv_command_len; unsigned char scpRecv_response[LIBSSH2_SCP_RESPONSE_BUFLEN]; size_t scpRecv_response_len; long scpRecv_mode; #if defined(HAVE_LONGLONG) && defined(HAVE_STRTOLL) /* we have the type and we can parse such numbers */ long long scpRecv_size; #define scpsize_strtol strtoll #elif defined(HAVE_STRTOI64) __int64 scpRecv_size; #define scpsize_strtol _strtoi64 #else long scpRecv_size; #define scpsize_strtol strtol #endif long scpRecv_mtime; long scpRecv_atime; LIBSSH2_CHANNEL *scpRecv_channel; /* State variables used in libssh2_scp_send_ex() */ libssh2_nonblocking_states scpSend_state; unsigned char *scpSend_command; size_t scpSend_command_len; unsigned char scpSend_response[LIBSSH2_SCP_RESPONSE_BUFLEN]; size_t scpSend_response_len; LIBSSH2_CHANNEL *scpSend_channel; /* Keepalive variables used by keepalive.c. */ int keepalive_interval; int keepalive_want_reply; time_t keepalive_last_sent; }; /* session.state bits */ #define LIBSSH2_STATE_EXCHANGING_KEYS 0x00000001 #define LIBSSH2_STATE_NEWKEYS 0x00000002 #define LIBSSH2_STATE_AUTHENTICATED 0x00000004 #define LIBSSH2_STATE_KEX_ACTIVE 0x00000008 /* session.flag helpers */ #ifdef MSG_NOSIGNAL #define LIBSSH2_SOCKET_SEND_FLAGS(session) \ (((session)->flag.sigpipe) ? 0 : MSG_NOSIGNAL) #define LIBSSH2_SOCKET_RECV_FLAGS(session) \ (((session)->flag.sigpipe) ? 0 : MSG_NOSIGNAL) #else /* If MSG_NOSIGNAL isn't defined we're SOL on blocking SIGPIPE */ #define LIBSSH2_SOCKET_SEND_FLAGS(session) 0 #define LIBSSH2_SOCKET_RECV_FLAGS(session) 0 #endif /* --------- */ /* libssh2 extensible ssh api, ultimately I'd like to allow loading additional methods via .so/.dll */ struct _LIBSSH2_KEX_METHOD { const char *name; /* Key exchange, populates session->* and returns 0 on success, non-0 on error */ int (*exchange_keys) (LIBSSH2_SESSION * session, key_exchange_state_low_t * key_state); long flags; }; struct _LIBSSH2_HOSTKEY_METHOD { const char *name; unsigned long hash_len; int (*init) (LIBSSH2_SESSION * session, const unsigned char *hostkey_data, size_t hostkey_data_len, void **abstract); int (*initPEM) (LIBSSH2_SESSION * session, const char *privkeyfile, unsigned const char *passphrase, void **abstract); int (*initPEMFromMemory) (LIBSSH2_SESSION * session, const char *privkeyfiledata, size_t privkeyfiledata_len, unsigned const char *passphrase, void **abstract); int (*sig_verify) (LIBSSH2_SESSION * session, const unsigned char *sig, size_t sig_len, const unsigned char *m, size_t m_len, void **abstract); int (*signv) (LIBSSH2_SESSION * session, unsigned char **signature, size_t *signature_len, int veccount, const struct iovec datavec[], void **abstract); int (*encrypt) (LIBSSH2_SESSION * session, unsigned char **dst, size_t *dst_len, const unsigned char *src, size_t src_len, void **abstract); int (*dtor) (LIBSSH2_SESSION * session, void **abstract); }; struct _LIBSSH2_CRYPT_METHOD { const char *name; int blocksize; /* iv and key sizes (-1 for variable length) */ int iv_len; int secret_len; long flags; int (*init) (LIBSSH2_SESSION * session, const LIBSSH2_CRYPT_METHOD * method, unsigned char *iv, int *free_iv, unsigned char *secret, int *free_secret, int encrypt, void **abstract); int (*crypt) (LIBSSH2_SESSION * session, unsigned char *block, size_t blocksize, void **abstract); int (*dtor) (LIBSSH2_SESSION * session, void **abstract); _libssh2_cipher_type(algo); }; struct _LIBSSH2_COMP_METHOD { const char *name; int compress; /* 1 if it does compress, 0 if it doesn't */ int use_in_auth; /* 1 if compression should be used in userauth */ int (*init) (LIBSSH2_SESSION *session, int compress, void **abstract); int (*comp) (LIBSSH2_SESSION *session, unsigned char *dest, size_t *dest_len, const unsigned char *src, size_t src_len, void **abstract); int (*decomp) (LIBSSH2_SESSION *session, unsigned char **dest, size_t *dest_len, size_t payload_limit, const unsigned char *src, size_t src_len, void **abstract); int (*dtor) (LIBSSH2_SESSION * session, int compress, void **abstract); }; #ifdef LIBSSH2DEBUG void _libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format, ...); #else #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || defined(__GNUC__) /* C99 supported and also by older GCC */ #define _libssh2_debug(x,y,z,...) do {} while (0) #else /* no gcc and not C99, do static and hopefully inline */ static inline void _libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format, ...) { (void)session; (void)context; (void)format; } #endif #endif #define LIBSSH2_SOCKET_UNKNOWN 1 #define LIBSSH2_SOCKET_CONNECTED 0 #define LIBSSH2_SOCKET_DISCONNECTED -1 /* Initial packet state, prior to MAC check */ #define LIBSSH2_MAC_UNCONFIRMED 1 /* When MAC type is "none" (proto initiation phase) all packets are deemed "confirmed" */ #define LIBSSH2_MAC_CONFIRMED 0 /* Something very bad is going on */ #define LIBSSH2_MAC_INVALID -1 /* Flags for _libssh2_error_flags */ /* Error message is allocated on the heap */ #define LIBSSH2_ERR_FLAG_DUP 1 /* SSH Packet Types -- Defined by internet draft */ /* Transport Layer */ #define SSH_MSG_DISCONNECT 1 #define SSH_MSG_IGNORE 2 #define SSH_MSG_UNIMPLEMENTED 3 #define SSH_MSG_DEBUG 4 #define SSH_MSG_SERVICE_REQUEST 5 #define SSH_MSG_SERVICE_ACCEPT 6 #define SSH_MSG_KEXINIT 20 #define SSH_MSG_NEWKEYS 21 /* diffie-hellman-group1-sha1 */ #define SSH_MSG_KEXDH_INIT 30 #define SSH_MSG_KEXDH_REPLY 31 /* diffie-hellman-group-exchange-sha1 and diffie-hellman-group-exchange-sha256 */ #define SSH_MSG_KEX_DH_GEX_REQUEST_OLD 30 #define SSH_MSG_KEX_DH_GEX_REQUEST 34 #define SSH_MSG_KEX_DH_GEX_GROUP 31 #define SSH_MSG_KEX_DH_GEX_INIT 32 #define SSH_MSG_KEX_DH_GEX_REPLY 33 /* User Authentication */ #define SSH_MSG_USERAUTH_REQUEST 50 #define SSH_MSG_USERAUTH_FAILURE 51 #define SSH_MSG_USERAUTH_SUCCESS 52 #define SSH_MSG_USERAUTH_BANNER 53 /* "public key" method */ #define SSH_MSG_USERAUTH_PK_OK 60 /* "password" method */ #define SSH_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* "keyboard-interactive" method */ #define SSH_MSG_USERAUTH_INFO_REQUEST 60 #define SSH_MSG_USERAUTH_INFO_RESPONSE 61 /* Channels */ #define SSH_MSG_GLOBAL_REQUEST 80 #define SSH_MSG_REQUEST_SUCCESS 81 #define SSH_MSG_REQUEST_FAILURE 82 #define SSH_MSG_CHANNEL_OPEN 90 #define SSH_MSG_CHANNEL_OPEN_CONFIRMATION 91 #define SSH_MSG_CHANNEL_OPEN_FAILURE 92 #define SSH_MSG_CHANNEL_WINDOW_ADJUST 93 #define SSH_MSG_CHANNEL_DATA 94 #define SSH_MSG_CHANNEL_EXTENDED_DATA 95 #define SSH_MSG_CHANNEL_EOF 96 #define SSH_MSG_CHANNEL_CLOSE 97 #define SSH_MSG_CHANNEL_REQUEST 98 #define SSH_MSG_CHANNEL_SUCCESS 99 #define SSH_MSG_CHANNEL_FAILURE 100 /* Error codes returned in SSH_MSG_CHANNEL_OPEN_FAILURE message (see RFC4254) */ #define SSH_OPEN_ADMINISTRATIVELY_PROHIBITED 1 #define SSH_OPEN_CONNECT_FAILED 2 #define SSH_OPEN_UNKNOWN_CHANNELTYPE 3 #define SSH_OPEN_RESOURCE_SHORTAGE 4 ssize_t _libssh2_recv(libssh2_socket_t socket, void *buffer, size_t length, int flags, void **abstract); ssize_t _libssh2_send(libssh2_socket_t socket, const void *buffer, size_t length, int flags, void **abstract); #define LIBSSH2_READ_TIMEOUT 60 /* generic timeout in seconds used when waiting for more data to arrive */ int _libssh2_kex_exchange(LIBSSH2_SESSION * session, int reexchange, key_exchange_state_t * state); /* Let crypt.c/hostkey.c expose their method structs */ const LIBSSH2_CRYPT_METHOD **libssh2_crypt_methods(void); const LIBSSH2_HOSTKEY_METHOD **libssh2_hostkey_methods(void); /* pem.c */ int _libssh2_pem_parse(LIBSSH2_SESSION * session, const char *headerbegin, const char *headerend, FILE * fp, unsigned char **data, unsigned int *datalen); int _libssh2_pem_parse_memory(LIBSSH2_SESSION * session, const char *headerbegin, const char *headerend, const char *filedata, size_t filedata_len, unsigned char **data, unsigned int *datalen); int _libssh2_pem_decode_sequence(unsigned char **data, unsigned int *datalen); int _libssh2_pem_decode_integer(unsigned char **data, unsigned int *datalen, unsigned char **i, unsigned int *ilen); /* global.c */ void _libssh2_init_if_needed (void); #define ARRAY_SIZE(a) (sizeof ((a)) / sizeof ((a)[0])) /* define to output the libssh2_int64_t type in a *printf() */ #if defined( __BORLANDC__ ) || defined( _MSC_VER ) || defined( __MINGW32__ ) #define LIBSSH2_INT64_T_FORMAT "I64d" #else #define LIBSSH2_INT64_T_FORMAT "lld" #endif #endif /* LIBSSH2_H */
36,504
C++
.h
897
35.430323
89
0.670965
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,274
libgcrypt.h
Studio3T_robomongo/src/third-party/libssh2-1.7.0/sources/src/libgcrypt.h
/* * Copyright (C) 2008, 2009, 2010 Simon Josefsson * Copyright (C) 2006, 2007, The Written Word, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #include <gcrypt.h> #define LIBSSH2_MD5 1 #define LIBSSH2_HMAC_RIPEMD 1 #define LIBSSH2_HMAC_SHA256 1 #define LIBSSH2_HMAC_SHA512 1 #define LIBSSH2_AES 1 #define LIBSSH2_AES_CTR 1 #define LIBSSH2_BLOWFISH 1 #define LIBSSH2_RC4 1 #define LIBSSH2_CAST 1 #define LIBSSH2_3DES 1 #define LIBSSH2_RSA 1 #define LIBSSH2_DSA 1 #define MD5_DIGEST_LENGTH 16 #define SHA_DIGEST_LENGTH 20 #define SHA256_DIGEST_LENGTH 32 #define _libssh2_random(buf, len) \ (gcry_randomize ((buf), (len), GCRY_STRONG_RANDOM), 1) #define libssh2_prepare_iovec(vec, len) /* Empty. */ #define libssh2_sha1_ctx gcry_md_hd_t /* returns 0 in case of failure */ #define libssh2_sha1_init(ctx) \ (GPG_ERR_NO_ERROR == gcry_md_open (ctx, GCRY_MD_SHA1, 0)) #define libssh2_sha1_update(ctx, data, len) \ gcry_md_write (ctx, (unsigned char *) data, len) #define libssh2_sha1_final(ctx, out) \ memcpy (out, gcry_md_read (ctx, 0), SHA_DIGEST_LENGTH), gcry_md_close (ctx) #define libssh2_sha1(message, len, out) \ gcry_md_hash_buffer (GCRY_MD_SHA1, out, message, len) #define libssh2_sha256_ctx gcry_md_hd_t #define libssh2_sha256_init(ctx) \ (GPG_ERR_NO_ERROR == gcry_md_open (ctx, GCRY_MD_SHA256, 0)) #define libssh2_sha256_update(ctx, data, len) \ gcry_md_write (ctx, (unsigned char *) data, len) #define libssh2_sha256_final(ctx, out) \ memcpy (out, gcry_md_read (ctx, 0), SHA256_DIGEST_LENGTH), gcry_md_close (ctx) #define libssh2_sha256(message, len, out) \ gcry_md_hash_buffer (GCRY_MD_SHA256, out, message, len) #define libssh2_md5_ctx gcry_md_hd_t /* returns 0 in case of failure */ #define libssh2_md5_init(ctx) \ (GPG_ERR_NO_ERROR == gcry_md_open (ctx, GCRY_MD_MD5, 0)) #define libssh2_md5_update(ctx, data, len) \ gcry_md_write (ctx, (unsigned char *) data, len) #define libssh2_md5_final(ctx, out) \ memcpy (out, gcry_md_read (ctx, 0), MD5_DIGEST_LENGTH), gcry_md_close (ctx) #define libssh2_md5(message, len, out) \ gcry_md_hash_buffer (GCRY_MD_MD5, out, message, len) #define libssh2_hmac_ctx gcry_md_hd_t #define libssh2_hmac_ctx_init(ctx) #define libssh2_hmac_sha1_init(ctx, key, keylen) \ gcry_md_open (ctx, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC), \ gcry_md_setkey (*ctx, key, keylen) #define libssh2_hmac_md5_init(ctx, key, keylen) \ gcry_md_open (ctx, GCRY_MD_MD5, GCRY_MD_FLAG_HMAC), \ gcry_md_setkey (*ctx, key, keylen) #define libssh2_hmac_ripemd160_init(ctx, key, keylen) \ gcry_md_open (ctx, GCRY_MD_RMD160, GCRY_MD_FLAG_HMAC), \ gcry_md_setkey (*ctx, key, keylen) #define libssh2_hmac_sha256_init(ctx, key, keylen) \ gcry_md_open (ctx, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC), \ gcry_md_setkey (*ctx, key, keylen) #define libssh2_hmac_sha512_init(ctx, key, keylen) \ gcry_md_open (ctx, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC), \ gcry_md_setkey (*ctx, key, keylen) #define libssh2_hmac_update(ctx, data, datalen) \ gcry_md_write (ctx, (unsigned char *) data, datalen) #define libssh2_hmac_final(ctx, data) \ memcpy (data, gcry_md_read (ctx, 0), \ gcry_md_get_algo_dlen (gcry_md_get_algo (ctx))) #define libssh2_hmac_cleanup(ctx) gcry_md_close (*ctx); #define libssh2_crypto_init() gcry_control (GCRYCTL_DISABLE_SECMEM) #define libssh2_crypto_exit() #define libssh2_rsa_ctx struct gcry_sexp #define _libssh2_rsa_free(rsactx) gcry_sexp_release (rsactx) #define libssh2_dsa_ctx struct gcry_sexp #define _libssh2_dsa_free(dsactx) gcry_sexp_release (dsactx) #define _libssh2_cipher_type(name) int name #define _libssh2_cipher_ctx gcry_cipher_hd_t #define _libssh2_gcry_ciphermode(c,m) ((c << 8) | m) #define _libssh2_gcry_cipher(c) (c >> 8) #define _libssh2_gcry_mode(m) (m & 0xFF) #define _libssh2_cipher_aes256ctr \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CTR) #define _libssh2_cipher_aes192ctr \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CTR) #define _libssh2_cipher_aes128ctr \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CTR) #define _libssh2_cipher_aes256 \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_aes192 \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_aes128 \ _libssh2_gcry_ciphermode(GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_blowfish \ _libssh2_gcry_ciphermode(GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_arcfour \ _libssh2_gcry_ciphermode(GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM) #define _libssh2_cipher_cast5 \ _libssh2_gcry_ciphermode(GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_3des \ _libssh2_gcry_ciphermode(GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_CBC) #define _libssh2_cipher_dtor(ctx) gcry_cipher_close(*(ctx)) #define _libssh2_bn struct gcry_mpi #define _libssh2_bn_ctx int #define _libssh2_bn_ctx_new() 0 #define _libssh2_bn_ctx_free(bnctx) ((void)0) #define _libssh2_bn_init() gcry_mpi_new(0) #define _libssh2_bn_init_from_bin() NULL /* because gcry_mpi_scan() creates a new bignum */ #define _libssh2_bn_rand(bn, bits, top, bottom) gcry_mpi_randomize (bn, bits, GCRY_WEAK_RANDOM) #define _libssh2_bn_mod_exp(r, a, p, m, ctx) gcry_mpi_powm (r, a, p, m) #define _libssh2_bn_set_word(bn, val) gcry_mpi_set_ui(bn, val) #define _libssh2_bn_from_bin(bn, len, val) gcry_mpi_scan(&((bn)), GCRYMPI_FMT_USG, val, len, NULL) #define _libssh2_bn_to_bin(bn, val) gcry_mpi_print (GCRYMPI_FMT_USG, val, _libssh2_bn_bytes(bn), NULL, bn) #define _libssh2_bn_bytes(bn) (gcry_mpi_get_nbits (bn) / 8 + ((gcry_mpi_get_nbits (bn) % 8 == 0) ? 0 : 1)) #define _libssh2_bn_bits(bn) gcry_mpi_get_nbits (bn) #define _libssh2_bn_free(bn) gcry_mpi_release(bn)
7,346
C++
.h
155
45.419355
106
0.736702
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,275
openssl.h
Studio3T_robomongo/src/third-party/libssh2-1.7.0/sources/src/openssl.h
/* Copyright (C) 2009, 2010 Simon Josefsson * Copyright (C) 2006, 2007 The Written Word, Inc. All rights reserved. * * Author: Simon Josefsson * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #include <openssl/opensslconf.h> #include <openssl/sha.h> #include <openssl/rsa.h> #include <openssl/engine.h> #ifndef OPENSSL_NO_DSA #include <openssl/dsa.h> #endif #ifndef OPENSSL_NO_MD5 #include <openssl/md5.h> #endif #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/bn.h> #include <openssl/pem.h> #include <openssl/rand.h> #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ !defined(LIBRESSL_VERSION_NUMBER) # define HAVE_OPAQUE_STRUCTS 1 #endif #ifdef OPENSSL_NO_RSA # define LIBSSH2_RSA 0 #else # define LIBSSH2_RSA 1 #endif #ifdef OPENSSL_NO_DSA # define LIBSSH2_DSA 0 #else # define LIBSSH2_DSA 1 #endif #ifdef OPENSSL_NO_MD5 # define LIBSSH2_MD5 0 #else # define LIBSSH2_MD5 1 #endif #ifdef OPENSSL_NO_RIPEMD # define LIBSSH2_HMAC_RIPEMD 0 #else # define LIBSSH2_HMAC_RIPEMD 1 #endif #define LIBSSH2_HMAC_SHA256 1 #define LIBSSH2_HMAC_SHA512 1 #if OPENSSL_VERSION_NUMBER >= 0x00907000L && !defined(OPENSSL_NO_AES) # define LIBSSH2_AES_CTR 1 # define LIBSSH2_AES 1 #else # define LIBSSH2_AES_CTR 0 # define LIBSSH2_AES 0 #endif #ifdef OPENSSL_NO_BF # define LIBSSH2_BLOWFISH 0 #else # define LIBSSH2_BLOWFISH 1 #endif #ifdef OPENSSL_NO_RC4 # define LIBSSH2_RC4 0 #else # define LIBSSH2_RC4 1 #endif #ifdef OPENSSL_NO_CAST # define LIBSSH2_CAST 0 #else # define LIBSSH2_CAST 1 #endif #ifdef OPENSSL_NO_DES # define LIBSSH2_3DES 0 #else # define LIBSSH2_3DES 1 #endif #define _libssh2_random(buf, len) RAND_bytes ((buf), (len)) #define libssh2_prepare_iovec(vec, len) /* Empty. */ #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha1_ctx EVP_MD_CTX * #else #define libssh2_sha1_ctx EVP_MD_CTX #endif /* returns 0 in case of failure */ int _libssh2_sha1_init(libssh2_sha1_ctx *ctx); #define libssh2_sha1_init(x) _libssh2_sha1_init(x) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha1_update(ctx, data, len) EVP_DigestUpdate(ctx, data, len) #define libssh2_sha1_final(ctx, out) do { \ EVP_DigestFinal(ctx, out, NULL); \ EVP_MD_CTX_free(ctx); \ } while(0) #else #define libssh2_sha1_update(ctx, data, len) EVP_DigestUpdate(&(ctx), data, len) #define libssh2_sha1_final(ctx, out) EVP_DigestFinal(&(ctx), out, NULL) #endif int _libssh2_sha1(const unsigned char *message, unsigned long len, unsigned char *out); #define libssh2_sha1(x,y,z) _libssh2_sha1(x,y,z) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha256_ctx EVP_MD_CTX * #else #define libssh2_sha256_ctx EVP_MD_CTX #endif /* returns 0 in case of failure */ int _libssh2_sha256_init(libssh2_sha256_ctx *ctx); #define libssh2_sha256_init(x) _libssh2_sha256_init(x) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_sha256_update(ctx, data, len) EVP_DigestUpdate(ctx, data, len) #define libssh2_sha256_final(ctx, out) do { \ EVP_DigestFinal(ctx, out, NULL); \ EVP_MD_CTX_free(ctx); \ } while(0) #else #define libssh2_sha256_update(ctx, data, len) EVP_DigestUpdate(&(ctx), data, len) #define libssh2_sha256_final(ctx, out) EVP_DigestFinal(&(ctx), out, NULL) #endif int _libssh2_sha256(const unsigned char *message, unsigned long len, unsigned char *out); #define libssh2_sha256(x,y,z) _libssh2_sha256(x,y,z) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_md5_ctx EVP_MD_CTX * #else #define libssh2_md5_ctx EVP_MD_CTX #endif /* returns 0 in case of failure */ int _libssh2_md5_init(libssh2_md5_ctx *ctx); #define libssh2_md5_init(x) _libssh2_md5_init(x) #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_md5_update(ctx, data, len) EVP_DigestUpdate(ctx, data, len) #define libssh2_md5_final(ctx, out) do { \ EVP_DigestFinal(ctx, out, NULL); \ EVP_MD_CTX_free(ctx); \ } while(0) #else #define libssh2_md5_update(ctx, data, len) EVP_DigestUpdate(&(ctx), data, len) #define libssh2_md5_final(ctx, out) EVP_DigestFinal(&(ctx), out, NULL) #endif #ifdef HAVE_OPAQUE_STRUCTS #define libssh2_hmac_ctx HMAC_CTX * #define libssh2_hmac_ctx_init(ctx) ctx = HMAC_CTX_new() #define libssh2_hmac_sha1_init(ctx, key, keylen) \ HMAC_Init_ex(*(ctx), key, keylen, EVP_sha1(), NULL) #define libssh2_hmac_md5_init(ctx, key, keylen) \ HMAC_Init_ex(*(ctx), key, keylen, EVP_md5(), NULL) #define libssh2_hmac_ripemd160_init(ctx, key, keylen) \ HMAC_Init_ex(*(ctx), key, keylen, EVP_ripemd160(), NULL) #define libssh2_hmac_sha256_init(ctx, key, keylen) \ HMAC_Init_ex(*(ctx), key, keylen, EVP_sha256(), NULL) #define libssh2_hmac_sha512_init(ctx, key, keylen) \ HMAC_Init_ex(*(ctx), key, keylen, EVP_sha512(), NULL) #define libssh2_hmac_update(ctx, data, datalen) \ HMAC_Update(ctx, data, datalen) #define libssh2_hmac_final(ctx, data) HMAC_Final(ctx, data, NULL) #define libssh2_hmac_cleanup(ctx) HMAC_CTX_free(*(ctx)) #else #define libssh2_hmac_ctx HMAC_CTX #define libssh2_hmac_ctx_init(ctx) \ HMAC_CTX_init(&ctx) #define libssh2_hmac_sha1_init(ctx, key, keylen) \ HMAC_Init_ex(ctx, key, keylen, EVP_sha1(), NULL) #define libssh2_hmac_md5_init(ctx, key, keylen) \ HMAC_Init_ex(ctx, key, keylen, EVP_md5(), NULL) #define libssh2_hmac_ripemd160_init(ctx, key, keylen) \ HMAC_Init_ex(ctx, key, keylen, EVP_ripemd160(), NULL) #define libssh2_hmac_sha256_init(ctx, key, keylen) \ HMAC_Init_ex(ctx, key, keylen, EVP_sha256(), NULL) #define libssh2_hmac_sha512_init(ctx, key, keylen) \ HMAC_Init_ex(ctx, key, keylen, EVP_sha512(), NULL) #define libssh2_hmac_update(ctx, data, datalen) \ HMAC_Update(&(ctx), data, datalen) #define libssh2_hmac_final(ctx, data) HMAC_Final(&(ctx), data, NULL) #define libssh2_hmac_cleanup(ctx) HMAC_cleanup(ctx) #endif #define libssh2_crypto_init() \ OpenSSL_add_all_algorithms(); \ ENGINE_load_builtin_engines(); \ ENGINE_register_all_complete() #define libssh2_crypto_exit() #define libssh2_rsa_ctx RSA #define _libssh2_rsa_free(rsactx) RSA_free(rsactx) #define libssh2_dsa_ctx DSA #define _libssh2_dsa_free(dsactx) DSA_free(dsactx) #define _libssh2_cipher_type(name) const EVP_CIPHER *(*name)(void) #ifdef HAVE_OPAQUE_STRUCTS #define _libssh2_cipher_ctx EVP_CIPHER_CTX * #else #define _libssh2_cipher_ctx EVP_CIPHER_CTX #endif #define _libssh2_cipher_aes256 EVP_aes_256_cbc #define _libssh2_cipher_aes192 EVP_aes_192_cbc #define _libssh2_cipher_aes128 EVP_aes_128_cbc #ifdef HAVE_EVP_AES_128_CTR #define _libssh2_cipher_aes128ctr EVP_aes_128_ctr #define _libssh2_cipher_aes192ctr EVP_aes_192_ctr #define _libssh2_cipher_aes256ctr EVP_aes_256_ctr #else #define _libssh2_cipher_aes128ctr _libssh2_EVP_aes_128_ctr #define _libssh2_cipher_aes192ctr _libssh2_EVP_aes_192_ctr #define _libssh2_cipher_aes256ctr _libssh2_EVP_aes_256_ctr #endif #define _libssh2_cipher_blowfish EVP_bf_cbc #define _libssh2_cipher_arcfour EVP_rc4 #define _libssh2_cipher_cast5 EVP_cast5_cbc #define _libssh2_cipher_3des EVP_des_ede3_cbc #ifdef HAVE_OPAQUE_STRUCTS #define _libssh2_cipher_dtor(ctx) EVP_CIPHER_CTX_reset(*(ctx)) #else #define _libssh2_cipher_dtor(ctx) EVP_CIPHER_CTX_cleanup(ctx) #endif #define _libssh2_bn BIGNUM #define _libssh2_bn_ctx BN_CTX #define _libssh2_bn_ctx_new() BN_CTX_new() #define _libssh2_bn_ctx_free(bnctx) BN_CTX_free(bnctx) #define _libssh2_bn_init() BN_new() #define _libssh2_bn_init_from_bin() _libssh2_bn_init() #define _libssh2_bn_rand(bn, bits, top, bottom) BN_rand(bn, bits, top, bottom) #define _libssh2_bn_mod_exp(r, a, p, m, ctx) BN_mod_exp(r, a, p, m, ctx) #define _libssh2_bn_set_word(bn, val) BN_set_word(bn, val) #define _libssh2_bn_from_bin(bn, len, val) BN_bin2bn(val, len, bn) #define _libssh2_bn_to_bin(bn, val) BN_bn2bin(bn, val) #define _libssh2_bn_bytes(bn) BN_num_bytes(bn) #define _libssh2_bn_bits(bn) BN_num_bits(bn) #define _libssh2_bn_free(bn) BN_clear_free(bn) const EVP_CIPHER *_libssh2_EVP_aes_128_ctr(void); const EVP_CIPHER *_libssh2_EVP_aes_192_ctr(void); const EVP_CIPHER *_libssh2_EVP_aes_256_ctr(void);
9,752
C++
.h
257
34.980545
81
0.723755
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,292
SciLexer.h
Studio3T_robomongo/src/third-party/qscintilla-2.8.4/sources/include/SciLexer.h
/* Scintilla source code edit control */ /** @file SciLexer.h ** Interface to the added lexer functions in the SciLexer version of the edit control. **/ /* Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org> * The License.txt file describes the conditions under which this software may be distributed. */ /* Most of this file is automatically generated from the Scintilla.iface interface definition * file which contains any comments about the definitions. HFacer.py does the generation. */ #ifndef SCILEXER_H #define SCILEXER_H /* SciLexer features - not in standard Scintilla */ /* ++Autogenerated -- start of section automatically generated from Scintilla.iface */ #define SCLEX_CONTAINER 0 #define SCLEX_NULL 1 #define SCLEX_PYTHON 2 #define SCLEX_CPP 3 #define SCLEX_HTML 4 #define SCLEX_XML 5 #define SCLEX_PERL 6 #define SCLEX_SQL 7 #define SCLEX_VB 8 #define SCLEX_PROPERTIES 9 #define SCLEX_ERRORLIST 10 #define SCLEX_MAKEFILE 11 #define SCLEX_BATCH 12 #define SCLEX_XCODE 13 #define SCLEX_LATEX 14 #define SCLEX_LUA 15 #define SCLEX_DIFF 16 #define SCLEX_CONF 17 #define SCLEX_PASCAL 18 #define SCLEX_AVE 19 #define SCLEX_ADA 20 #define SCLEX_LISP 21 #define SCLEX_RUBY 22 #define SCLEX_EIFFEL 23 #define SCLEX_EIFFELKW 24 #define SCLEX_TCL 25 #define SCLEX_NNCRONTAB 26 #define SCLEX_BULLANT 27 #define SCLEX_VBSCRIPT 28 #define SCLEX_BAAN 31 #define SCLEX_MATLAB 32 #define SCLEX_SCRIPTOL 33 #define SCLEX_ASM 34 #define SCLEX_CPPNOCASE 35 #define SCLEX_FORTRAN 36 #define SCLEX_F77 37 #define SCLEX_CSS 38 #define SCLEX_POV 39 #define SCLEX_LOUT 40 #define SCLEX_ESCRIPT 41 #define SCLEX_PS 42 #define SCLEX_NSIS 43 #define SCLEX_MMIXAL 44 #define SCLEX_CLW 45 #define SCLEX_CLWNOCASE 46 #define SCLEX_LOT 47 #define SCLEX_YAML 48 #define SCLEX_TEX 49 #define SCLEX_METAPOST 50 #define SCLEX_POWERBASIC 51 #define SCLEX_FORTH 52 #define SCLEX_ERLANG 53 #define SCLEX_OCTAVE 54 #define SCLEX_MSSQL 55 #define SCLEX_VERILOG 56 #define SCLEX_KIX 57 #define SCLEX_GUI4CLI 58 #define SCLEX_SPECMAN 59 #define SCLEX_AU3 60 #define SCLEX_APDL 61 #define SCLEX_BASH 62 #define SCLEX_ASN1 63 #define SCLEX_VHDL 64 #define SCLEX_CAML 65 #define SCLEX_BLITZBASIC 66 #define SCLEX_PUREBASIC 67 #define SCLEX_HASKELL 68 #define SCLEX_PHPSCRIPT 69 #define SCLEX_TADS3 70 #define SCLEX_REBOL 71 #define SCLEX_SMALLTALK 72 #define SCLEX_FLAGSHIP 73 #define SCLEX_CSOUND 74 #define SCLEX_FREEBASIC 75 #define SCLEX_INNOSETUP 76 #define SCLEX_OPAL 77 #define SCLEX_SPICE 78 #define SCLEX_D 79 #define SCLEX_CMAKE 80 #define SCLEX_GAP 81 #define SCLEX_PLM 82 #define SCLEX_PROGRESS 83 #define SCLEX_ABAQUS 84 #define SCLEX_ASYMPTOTE 85 #define SCLEX_R 86 #define SCLEX_MAGIK 87 #define SCLEX_POWERSHELL 88 #define SCLEX_MYSQL 89 #define SCLEX_PO 90 #define SCLEX_TAL 91 #define SCLEX_COBOL 92 #define SCLEX_TACL 93 #define SCLEX_SORCUS 94 #define SCLEX_POWERPRO 95 #define SCLEX_NIMROD 96 #define SCLEX_SML 97 #define SCLEX_MARKDOWN 98 #define SCLEX_TXT2TAGS 99 #define SCLEX_A68K 100 #define SCLEX_MODULA 101 #define SCLEX_COFFEESCRIPT 102 #define SCLEX_TCMD 103 #define SCLEX_AVS 104 #define SCLEX_ECL 105 #define SCLEX_OSCRIPT 106 #define SCLEX_VISUALPROLOG 107 #define SCLEX_LITERATEHASKELL 108 #define SCLEX_STTXT 109 #define SCLEX_KVIRC 110 #define SCLEX_RUST 111 #define SCLEX_AUTOMATIC 1000 #define SCE_P_DEFAULT 0 #define SCE_P_COMMENTLINE 1 #define SCE_P_NUMBER 2 #define SCE_P_STRING 3 #define SCE_P_CHARACTER 4 #define SCE_P_WORD 5 #define SCE_P_TRIPLE 6 #define SCE_P_TRIPLEDOUBLE 7 #define SCE_P_CLASSNAME 8 #define SCE_P_DEFNAME 9 #define SCE_P_OPERATOR 10 #define SCE_P_IDENTIFIER 11 #define SCE_P_COMMENTBLOCK 12 #define SCE_P_STRINGEOL 13 #define SCE_P_WORD2 14 #define SCE_P_DECORATOR 15 #define SCE_C_DEFAULT 0 #define SCE_C_COMMENT 1 #define SCE_C_COMMENTLINE 2 #define SCE_C_COMMENTDOC 3 #define SCE_C_NUMBER 4 #define SCE_C_WORD 5 #define SCE_C_STRING 6 #define SCE_C_CHARACTER 7 #define SCE_C_UUID 8 #define SCE_C_PREPROCESSOR 9 #define SCE_C_OPERATOR 10 #define SCE_C_IDENTIFIER 11 #define SCE_C_STRINGEOL 12 #define SCE_C_VERBATIM 13 #define SCE_C_REGEX 14 #define SCE_C_COMMENTLINEDOC 15 #define SCE_C_WORD2 16 #define SCE_C_COMMENTDOCKEYWORD 17 #define SCE_C_COMMENTDOCKEYWORDERROR 18 #define SCE_C_GLOBALCLASS 19 #define SCE_C_STRINGRAW 20 #define SCE_C_TRIPLEVERBATIM 21 #define SCE_C_HASHQUOTEDSTRING 22 #define SCE_C_PREPROCESSORCOMMENT 23 #define SCE_C_PREPROCESSORCOMMENTDOC 24 #define SCE_D_DEFAULT 0 #define SCE_D_COMMENT 1 #define SCE_D_COMMENTLINE 2 #define SCE_D_COMMENTDOC 3 #define SCE_D_COMMENTNESTED 4 #define SCE_D_NUMBER 5 #define SCE_D_WORD 6 #define SCE_D_WORD2 7 #define SCE_D_WORD3 8 #define SCE_D_TYPEDEF 9 #define SCE_D_STRING 10 #define SCE_D_STRINGEOL 11 #define SCE_D_CHARACTER 12 #define SCE_D_OPERATOR 13 #define SCE_D_IDENTIFIER 14 #define SCE_D_COMMENTLINEDOC 15 #define SCE_D_COMMENTDOCKEYWORD 16 #define SCE_D_COMMENTDOCKEYWORDERROR 17 #define SCE_D_STRINGB 18 #define SCE_D_STRINGR 19 #define SCE_D_WORD5 20 #define SCE_D_WORD6 21 #define SCE_D_WORD7 22 #define SCE_TCL_DEFAULT 0 #define SCE_TCL_COMMENT 1 #define SCE_TCL_COMMENTLINE 2 #define SCE_TCL_NUMBER 3 #define SCE_TCL_WORD_IN_QUOTE 4 #define SCE_TCL_IN_QUOTE 5 #define SCE_TCL_OPERATOR 6 #define SCE_TCL_IDENTIFIER 7 #define SCE_TCL_SUBSTITUTION 8 #define SCE_TCL_SUB_BRACE 9 #define SCE_TCL_MODIFIER 10 #define SCE_TCL_EXPAND 11 #define SCE_TCL_WORD 12 #define SCE_TCL_WORD2 13 #define SCE_TCL_WORD3 14 #define SCE_TCL_WORD4 15 #define SCE_TCL_WORD5 16 #define SCE_TCL_WORD6 17 #define SCE_TCL_WORD7 18 #define SCE_TCL_WORD8 19 #define SCE_TCL_COMMENT_BOX 20 #define SCE_TCL_BLOCK_COMMENT 21 #define SCE_H_DEFAULT 0 #define SCE_H_TAG 1 #define SCE_H_TAGUNKNOWN 2 #define SCE_H_ATTRIBUTE 3 #define SCE_H_ATTRIBUTEUNKNOWN 4 #define SCE_H_NUMBER 5 #define SCE_H_DOUBLESTRING 6 #define SCE_H_SINGLESTRING 7 #define SCE_H_OTHER 8 #define SCE_H_COMMENT 9 #define SCE_H_ENTITY 10 #define SCE_H_TAGEND 11 #define SCE_H_XMLSTART 12 #define SCE_H_XMLEND 13 #define SCE_H_SCRIPT 14 #define SCE_H_ASP 15 #define SCE_H_ASPAT 16 #define SCE_H_CDATA 17 #define SCE_H_QUESTION 18 #define SCE_H_VALUE 19 #define SCE_H_XCCOMMENT 20 #define SCE_H_SGML_DEFAULT 21 #define SCE_H_SGML_COMMAND 22 #define SCE_H_SGML_1ST_PARAM 23 #define SCE_H_SGML_DOUBLESTRING 24 #define SCE_H_SGML_SIMPLESTRING 25 #define SCE_H_SGML_ERROR 26 #define SCE_H_SGML_SPECIAL 27 #define SCE_H_SGML_ENTITY 28 #define SCE_H_SGML_COMMENT 29 #define SCE_H_SGML_1ST_PARAM_COMMENT 30 #define SCE_H_SGML_BLOCK_DEFAULT 31 #define SCE_HJ_START 40 #define SCE_HJ_DEFAULT 41 #define SCE_HJ_COMMENT 42 #define SCE_HJ_COMMENTLINE 43 #define SCE_HJ_COMMENTDOC 44 #define SCE_HJ_NUMBER 45 #define SCE_HJ_WORD 46 #define SCE_HJ_KEYWORD 47 #define SCE_HJ_DOUBLESTRING 48 #define SCE_HJ_SINGLESTRING 49 #define SCE_HJ_SYMBOLS 50 #define SCE_HJ_STRINGEOL 51 #define SCE_HJ_REGEX 52 #define SCE_HJA_START 55 #define SCE_HJA_DEFAULT 56 #define SCE_HJA_COMMENT 57 #define SCE_HJA_COMMENTLINE 58 #define SCE_HJA_COMMENTDOC 59 #define SCE_HJA_NUMBER 60 #define SCE_HJA_WORD 61 #define SCE_HJA_KEYWORD 62 #define SCE_HJA_DOUBLESTRING 63 #define SCE_HJA_SINGLESTRING 64 #define SCE_HJA_SYMBOLS 65 #define SCE_HJA_STRINGEOL 66 #define SCE_HJA_REGEX 67 #define SCE_HB_START 70 #define SCE_HB_DEFAULT 71 #define SCE_HB_COMMENTLINE 72 #define SCE_HB_NUMBER 73 #define SCE_HB_WORD 74 #define SCE_HB_STRING 75 #define SCE_HB_IDENTIFIER 76 #define SCE_HB_STRINGEOL 77 #define SCE_HBA_START 80 #define SCE_HBA_DEFAULT 81 #define SCE_HBA_COMMENTLINE 82 #define SCE_HBA_NUMBER 83 #define SCE_HBA_WORD 84 #define SCE_HBA_STRING 85 #define SCE_HBA_IDENTIFIER 86 #define SCE_HBA_STRINGEOL 87 #define SCE_HP_START 90 #define SCE_HP_DEFAULT 91 #define SCE_HP_COMMENTLINE 92 #define SCE_HP_NUMBER 93 #define SCE_HP_STRING 94 #define SCE_HP_CHARACTER 95 #define SCE_HP_WORD 96 #define SCE_HP_TRIPLE 97 #define SCE_HP_TRIPLEDOUBLE 98 #define SCE_HP_CLASSNAME 99 #define SCE_HP_DEFNAME 100 #define SCE_HP_OPERATOR 101 #define SCE_HP_IDENTIFIER 102 #define SCE_HPHP_COMPLEX_VARIABLE 104 #define SCE_HPA_START 105 #define SCE_HPA_DEFAULT 106 #define SCE_HPA_COMMENTLINE 107 #define SCE_HPA_NUMBER 108 #define SCE_HPA_STRING 109 #define SCE_HPA_CHARACTER 110 #define SCE_HPA_WORD 111 #define SCE_HPA_TRIPLE 112 #define SCE_HPA_TRIPLEDOUBLE 113 #define SCE_HPA_CLASSNAME 114 #define SCE_HPA_DEFNAME 115 #define SCE_HPA_OPERATOR 116 #define SCE_HPA_IDENTIFIER 117 #define SCE_HPHP_DEFAULT 118 #define SCE_HPHP_HSTRING 119 #define SCE_HPHP_SIMPLESTRING 120 #define SCE_HPHP_WORD 121 #define SCE_HPHP_NUMBER 122 #define SCE_HPHP_VARIABLE 123 #define SCE_HPHP_COMMENT 124 #define SCE_HPHP_COMMENTLINE 125 #define SCE_HPHP_HSTRING_VARIABLE 126 #define SCE_HPHP_OPERATOR 127 #define SCE_PL_DEFAULT 0 #define SCE_PL_ERROR 1 #define SCE_PL_COMMENTLINE 2 #define SCE_PL_POD 3 #define SCE_PL_NUMBER 4 #define SCE_PL_WORD 5 #define SCE_PL_STRING 6 #define SCE_PL_CHARACTER 7 #define SCE_PL_PUNCTUATION 8 #define SCE_PL_PREPROCESSOR 9 #define SCE_PL_OPERATOR 10 #define SCE_PL_IDENTIFIER 11 #define SCE_PL_SCALAR 12 #define SCE_PL_ARRAY 13 #define SCE_PL_HASH 14 #define SCE_PL_SYMBOLTABLE 15 #define SCE_PL_VARIABLE_INDEXER 16 #define SCE_PL_REGEX 17 #define SCE_PL_REGSUBST 18 #define SCE_PL_LONGQUOTE 19 #define SCE_PL_BACKTICKS 20 #define SCE_PL_DATASECTION 21 #define SCE_PL_HERE_DELIM 22 #define SCE_PL_HERE_Q 23 #define SCE_PL_HERE_QQ 24 #define SCE_PL_HERE_QX 25 #define SCE_PL_STRING_Q 26 #define SCE_PL_STRING_QQ 27 #define SCE_PL_STRING_QX 28 #define SCE_PL_STRING_QR 29 #define SCE_PL_STRING_QW 30 #define SCE_PL_POD_VERB 31 #define SCE_PL_SUB_PROTOTYPE 40 #define SCE_PL_FORMAT_IDENT 41 #define SCE_PL_FORMAT 42 #define SCE_PL_STRING_VAR 43 #define SCE_PL_XLAT 44 #define SCE_PL_REGEX_VAR 54 #define SCE_PL_REGSUBST_VAR 55 #define SCE_PL_BACKTICKS_VAR 57 #define SCE_PL_HERE_QQ_VAR 61 #define SCE_PL_HERE_QX_VAR 62 #define SCE_PL_STRING_QQ_VAR 64 #define SCE_PL_STRING_QX_VAR 65 #define SCE_PL_STRING_QR_VAR 66 #define SCE_RB_DEFAULT 0 #define SCE_RB_ERROR 1 #define SCE_RB_COMMENTLINE 2 #define SCE_RB_POD 3 #define SCE_RB_NUMBER 4 #define SCE_RB_WORD 5 #define SCE_RB_STRING 6 #define SCE_RB_CHARACTER 7 #define SCE_RB_CLASSNAME 8 #define SCE_RB_DEFNAME 9 #define SCE_RB_OPERATOR 10 #define SCE_RB_IDENTIFIER 11 #define SCE_RB_REGEX 12 #define SCE_RB_GLOBAL 13 #define SCE_RB_SYMBOL 14 #define SCE_RB_MODULE_NAME 15 #define SCE_RB_INSTANCE_VAR 16 #define SCE_RB_CLASS_VAR 17 #define SCE_RB_BACKTICKS 18 #define SCE_RB_DATASECTION 19 #define SCE_RB_HERE_DELIM 20 #define SCE_RB_HERE_Q 21 #define SCE_RB_HERE_QQ 22 #define SCE_RB_HERE_QX 23 #define SCE_RB_STRING_Q 24 #define SCE_RB_STRING_QQ 25 #define SCE_RB_STRING_QX 26 #define SCE_RB_STRING_QR 27 #define SCE_RB_STRING_QW 28 #define SCE_RB_WORD_DEMOTED 29 #define SCE_RB_STDIN 30 #define SCE_RB_STDOUT 31 #define SCE_RB_STDERR 40 #define SCE_RB_UPPER_BOUND 41 #define SCE_B_DEFAULT 0 #define SCE_B_COMMENT 1 #define SCE_B_NUMBER 2 #define SCE_B_KEYWORD 3 #define SCE_B_STRING 4 #define SCE_B_PREPROCESSOR 5 #define SCE_B_OPERATOR 6 #define SCE_B_IDENTIFIER 7 #define SCE_B_DATE 8 #define SCE_B_STRINGEOL 9 #define SCE_B_KEYWORD2 10 #define SCE_B_KEYWORD3 11 #define SCE_B_KEYWORD4 12 #define SCE_B_CONSTANT 13 #define SCE_B_ASM 14 #define SCE_B_LABEL 15 #define SCE_B_ERROR 16 #define SCE_B_HEXNUMBER 17 #define SCE_B_BINNUMBER 18 #define SCE_PROPS_DEFAULT 0 #define SCE_PROPS_COMMENT 1 #define SCE_PROPS_SECTION 2 #define SCE_PROPS_ASSIGNMENT 3 #define SCE_PROPS_DEFVAL 4 #define SCE_PROPS_KEY 5 #define SCE_L_DEFAULT 0 #define SCE_L_COMMAND 1 #define SCE_L_TAG 2 #define SCE_L_MATH 3 #define SCE_L_COMMENT 4 #define SCE_L_TAG2 5 #define SCE_L_MATH2 6 #define SCE_L_COMMENT2 7 #define SCE_L_VERBATIM 8 #define SCE_L_SHORTCMD 9 #define SCE_L_SPECIAL 10 #define SCE_L_CMDOPT 11 #define SCE_L_ERROR 12 #define SCE_LUA_DEFAULT 0 #define SCE_LUA_COMMENT 1 #define SCE_LUA_COMMENTLINE 2 #define SCE_LUA_COMMENTDOC 3 #define SCE_LUA_NUMBER 4 #define SCE_LUA_WORD 5 #define SCE_LUA_STRING 6 #define SCE_LUA_CHARACTER 7 #define SCE_LUA_LITERALSTRING 8 #define SCE_LUA_PREPROCESSOR 9 #define SCE_LUA_OPERATOR 10 #define SCE_LUA_IDENTIFIER 11 #define SCE_LUA_STRINGEOL 12 #define SCE_LUA_WORD2 13 #define SCE_LUA_WORD3 14 #define SCE_LUA_WORD4 15 #define SCE_LUA_WORD5 16 #define SCE_LUA_WORD6 17 #define SCE_LUA_WORD7 18 #define SCE_LUA_WORD8 19 #define SCE_LUA_LABEL 20 #define SCE_ERR_DEFAULT 0 #define SCE_ERR_PYTHON 1 #define SCE_ERR_GCC 2 #define SCE_ERR_MS 3 #define SCE_ERR_CMD 4 #define SCE_ERR_BORLAND 5 #define SCE_ERR_PERL 6 #define SCE_ERR_NET 7 #define SCE_ERR_LUA 8 #define SCE_ERR_CTAG 9 #define SCE_ERR_DIFF_CHANGED 10 #define SCE_ERR_DIFF_ADDITION 11 #define SCE_ERR_DIFF_DELETION 12 #define SCE_ERR_DIFF_MESSAGE 13 #define SCE_ERR_PHP 14 #define SCE_ERR_ELF 15 #define SCE_ERR_IFC 16 #define SCE_ERR_IFORT 17 #define SCE_ERR_ABSF 18 #define SCE_ERR_TIDY 19 #define SCE_ERR_JAVA_STACK 20 #define SCE_ERR_VALUE 21 #define SCE_ERR_GCC_INCLUDED_FROM 22 #define SCE_BAT_DEFAULT 0 #define SCE_BAT_COMMENT 1 #define SCE_BAT_WORD 2 #define SCE_BAT_LABEL 3 #define SCE_BAT_HIDE 4 #define SCE_BAT_COMMAND 5 #define SCE_BAT_IDENTIFIER 6 #define SCE_BAT_OPERATOR 7 #define SCE_TCMD_DEFAULT 0 #define SCE_TCMD_COMMENT 1 #define SCE_TCMD_WORD 2 #define SCE_TCMD_LABEL 3 #define SCE_TCMD_HIDE 4 #define SCE_TCMD_COMMAND 5 #define SCE_TCMD_IDENTIFIER 6 #define SCE_TCMD_OPERATOR 7 #define SCE_TCMD_ENVIRONMENT 8 #define SCE_TCMD_EXPANSION 9 #define SCE_TCMD_CLABEL 10 #define SCE_MAKE_DEFAULT 0 #define SCE_MAKE_COMMENT 1 #define SCE_MAKE_PREPROCESSOR 2 #define SCE_MAKE_IDENTIFIER 3 #define SCE_MAKE_OPERATOR 4 #define SCE_MAKE_TARGET 5 #define SCE_MAKE_IDEOL 9 #define SCE_DIFF_DEFAULT 0 #define SCE_DIFF_COMMENT 1 #define SCE_DIFF_COMMAND 2 #define SCE_DIFF_HEADER 3 #define SCE_DIFF_POSITION 4 #define SCE_DIFF_DELETED 5 #define SCE_DIFF_ADDED 6 #define SCE_DIFF_CHANGED 7 #define SCE_CONF_DEFAULT 0 #define SCE_CONF_COMMENT 1 #define SCE_CONF_NUMBER 2 #define SCE_CONF_IDENTIFIER 3 #define SCE_CONF_EXTENSION 4 #define SCE_CONF_PARAMETER 5 #define SCE_CONF_STRING 6 #define SCE_CONF_OPERATOR 7 #define SCE_CONF_IP 8 #define SCE_CONF_DIRECTIVE 9 #define SCE_AVE_DEFAULT 0 #define SCE_AVE_COMMENT 1 #define SCE_AVE_NUMBER 2 #define SCE_AVE_WORD 3 #define SCE_AVE_STRING 6 #define SCE_AVE_ENUM 7 #define SCE_AVE_STRINGEOL 8 #define SCE_AVE_IDENTIFIER 9 #define SCE_AVE_OPERATOR 10 #define SCE_AVE_WORD1 11 #define SCE_AVE_WORD2 12 #define SCE_AVE_WORD3 13 #define SCE_AVE_WORD4 14 #define SCE_AVE_WORD5 15 #define SCE_AVE_WORD6 16 #define SCE_ADA_DEFAULT 0 #define SCE_ADA_WORD 1 #define SCE_ADA_IDENTIFIER 2 #define SCE_ADA_NUMBER 3 #define SCE_ADA_DELIMITER 4 #define SCE_ADA_CHARACTER 5 #define SCE_ADA_CHARACTEREOL 6 #define SCE_ADA_STRING 7 #define SCE_ADA_STRINGEOL 8 #define SCE_ADA_LABEL 9 #define SCE_ADA_COMMENTLINE 10 #define SCE_ADA_ILLEGAL 11 #define SCE_BAAN_DEFAULT 0 #define SCE_BAAN_COMMENT 1 #define SCE_BAAN_COMMENTDOC 2 #define SCE_BAAN_NUMBER 3 #define SCE_BAAN_WORD 4 #define SCE_BAAN_STRING 5 #define SCE_BAAN_PREPROCESSOR 6 #define SCE_BAAN_OPERATOR 7 #define SCE_BAAN_IDENTIFIER 8 #define SCE_BAAN_STRINGEOL 9 #define SCE_BAAN_WORD2 10 #define SCE_LISP_DEFAULT 0 #define SCE_LISP_COMMENT 1 #define SCE_LISP_NUMBER 2 #define SCE_LISP_KEYWORD 3 #define SCE_LISP_KEYWORD_KW 4 #define SCE_LISP_SYMBOL 5 #define SCE_LISP_STRING 6 #define SCE_LISP_STRINGEOL 8 #define SCE_LISP_IDENTIFIER 9 #define SCE_LISP_OPERATOR 10 #define SCE_LISP_SPECIAL 11 #define SCE_LISP_MULTI_COMMENT 12 #define SCE_EIFFEL_DEFAULT 0 #define SCE_EIFFEL_COMMENTLINE 1 #define SCE_EIFFEL_NUMBER 2 #define SCE_EIFFEL_WORD 3 #define SCE_EIFFEL_STRING 4 #define SCE_EIFFEL_CHARACTER 5 #define SCE_EIFFEL_OPERATOR 6 #define SCE_EIFFEL_IDENTIFIER 7 #define SCE_EIFFEL_STRINGEOL 8 #define SCE_NNCRONTAB_DEFAULT 0 #define SCE_NNCRONTAB_COMMENT 1 #define SCE_NNCRONTAB_TASK 2 #define SCE_NNCRONTAB_SECTION 3 #define SCE_NNCRONTAB_KEYWORD 4 #define SCE_NNCRONTAB_MODIFIER 5 #define SCE_NNCRONTAB_ASTERISK 6 #define SCE_NNCRONTAB_NUMBER 7 #define SCE_NNCRONTAB_STRING 8 #define SCE_NNCRONTAB_ENVIRONMENT 9 #define SCE_NNCRONTAB_IDENTIFIER 10 #define SCE_FORTH_DEFAULT 0 #define SCE_FORTH_COMMENT 1 #define SCE_FORTH_COMMENT_ML 2 #define SCE_FORTH_IDENTIFIER 3 #define SCE_FORTH_CONTROL 4 #define SCE_FORTH_KEYWORD 5 #define SCE_FORTH_DEFWORD 6 #define SCE_FORTH_PREWORD1 7 #define SCE_FORTH_PREWORD2 8 #define SCE_FORTH_NUMBER 9 #define SCE_FORTH_STRING 10 #define SCE_FORTH_LOCALE 11 #define SCE_MATLAB_DEFAULT 0 #define SCE_MATLAB_COMMENT 1 #define SCE_MATLAB_COMMAND 2 #define SCE_MATLAB_NUMBER 3 #define SCE_MATLAB_KEYWORD 4 #define SCE_MATLAB_STRING 5 #define SCE_MATLAB_OPERATOR 6 #define SCE_MATLAB_IDENTIFIER 7 #define SCE_MATLAB_DOUBLEQUOTESTRING 8 #define SCE_SCRIPTOL_DEFAULT 0 #define SCE_SCRIPTOL_WHITE 1 #define SCE_SCRIPTOL_COMMENTLINE 2 #define SCE_SCRIPTOL_PERSISTENT 3 #define SCE_SCRIPTOL_CSTYLE 4 #define SCE_SCRIPTOL_COMMENTBLOCK 5 #define SCE_SCRIPTOL_NUMBER 6 #define SCE_SCRIPTOL_STRING 7 #define SCE_SCRIPTOL_CHARACTER 8 #define SCE_SCRIPTOL_STRINGEOL 9 #define SCE_SCRIPTOL_KEYWORD 10 #define SCE_SCRIPTOL_OPERATOR 11 #define SCE_SCRIPTOL_IDENTIFIER 12 #define SCE_SCRIPTOL_TRIPLE 13 #define SCE_SCRIPTOL_CLASSNAME 14 #define SCE_SCRIPTOL_PREPROCESSOR 15 #define SCE_ASM_DEFAULT 0 #define SCE_ASM_COMMENT 1 #define SCE_ASM_NUMBER 2 #define SCE_ASM_STRING 3 #define SCE_ASM_OPERATOR 4 #define SCE_ASM_IDENTIFIER 5 #define SCE_ASM_CPUINSTRUCTION 6 #define SCE_ASM_MATHINSTRUCTION 7 #define SCE_ASM_REGISTER 8 #define SCE_ASM_DIRECTIVE 9 #define SCE_ASM_DIRECTIVEOPERAND 10 #define SCE_ASM_COMMENTBLOCK 11 #define SCE_ASM_CHARACTER 12 #define SCE_ASM_STRINGEOL 13 #define SCE_ASM_EXTINSTRUCTION 14 #define SCE_ASM_COMMENTDIRECTIVE 15 #define SCE_F_DEFAULT 0 #define SCE_F_COMMENT 1 #define SCE_F_NUMBER 2 #define SCE_F_STRING1 3 #define SCE_F_STRING2 4 #define SCE_F_STRINGEOL 5 #define SCE_F_OPERATOR 6 #define SCE_F_IDENTIFIER 7 #define SCE_F_WORD 8 #define SCE_F_WORD2 9 #define SCE_F_WORD3 10 #define SCE_F_PREPROCESSOR 11 #define SCE_F_OPERATOR2 12 #define SCE_F_LABEL 13 #define SCE_F_CONTINUATION 14 #define SCE_CSS_DEFAULT 0 #define SCE_CSS_TAG 1 #define SCE_CSS_CLASS 2 #define SCE_CSS_PSEUDOCLASS 3 #define SCE_CSS_UNKNOWN_PSEUDOCLASS 4 #define SCE_CSS_OPERATOR 5 #define SCE_CSS_IDENTIFIER 6 #define SCE_CSS_UNKNOWN_IDENTIFIER 7 #define SCE_CSS_VALUE 8 #define SCE_CSS_COMMENT 9 #define SCE_CSS_ID 10 #define SCE_CSS_IMPORTANT 11 #define SCE_CSS_DIRECTIVE 12 #define SCE_CSS_DOUBLESTRING 13 #define SCE_CSS_SINGLESTRING 14 #define SCE_CSS_IDENTIFIER2 15 #define SCE_CSS_ATTRIBUTE 16 #define SCE_CSS_IDENTIFIER3 17 #define SCE_CSS_PSEUDOELEMENT 18 #define SCE_CSS_EXTENDED_IDENTIFIER 19 #define SCE_CSS_EXTENDED_PSEUDOCLASS 20 #define SCE_CSS_EXTENDED_PSEUDOELEMENT 21 #define SCE_CSS_MEDIA 22 #define SCE_CSS_VARIABLE 23 #define SCE_POV_DEFAULT 0 #define SCE_POV_COMMENT 1 #define SCE_POV_COMMENTLINE 2 #define SCE_POV_NUMBER 3 #define SCE_POV_OPERATOR 4 #define SCE_POV_IDENTIFIER 5 #define SCE_POV_STRING 6 #define SCE_POV_STRINGEOL 7 #define SCE_POV_DIRECTIVE 8 #define SCE_POV_BADDIRECTIVE 9 #define SCE_POV_WORD2 10 #define SCE_POV_WORD3 11 #define SCE_POV_WORD4 12 #define SCE_POV_WORD5 13 #define SCE_POV_WORD6 14 #define SCE_POV_WORD7 15 #define SCE_POV_WORD8 16 #define SCE_LOUT_DEFAULT 0 #define SCE_LOUT_COMMENT 1 #define SCE_LOUT_NUMBER 2 #define SCE_LOUT_WORD 3 #define SCE_LOUT_WORD2 4 #define SCE_LOUT_WORD3 5 #define SCE_LOUT_WORD4 6 #define SCE_LOUT_STRING 7 #define SCE_LOUT_OPERATOR 8 #define SCE_LOUT_IDENTIFIER 9 #define SCE_LOUT_STRINGEOL 10 #define SCE_ESCRIPT_DEFAULT 0 #define SCE_ESCRIPT_COMMENT 1 #define SCE_ESCRIPT_COMMENTLINE 2 #define SCE_ESCRIPT_COMMENTDOC 3 #define SCE_ESCRIPT_NUMBER 4 #define SCE_ESCRIPT_WORD 5 #define SCE_ESCRIPT_STRING 6 #define SCE_ESCRIPT_OPERATOR 7 #define SCE_ESCRIPT_IDENTIFIER 8 #define SCE_ESCRIPT_BRACE 9 #define SCE_ESCRIPT_WORD2 10 #define SCE_ESCRIPT_WORD3 11 #define SCE_PS_DEFAULT 0 #define SCE_PS_COMMENT 1 #define SCE_PS_DSC_COMMENT 2 #define SCE_PS_DSC_VALUE 3 #define SCE_PS_NUMBER 4 #define SCE_PS_NAME 5 #define SCE_PS_KEYWORD 6 #define SCE_PS_LITERAL 7 #define SCE_PS_IMMEVAL 8 #define SCE_PS_PAREN_ARRAY 9 #define SCE_PS_PAREN_DICT 10 #define SCE_PS_PAREN_PROC 11 #define SCE_PS_TEXT 12 #define SCE_PS_HEXSTRING 13 #define SCE_PS_BASE85STRING 14 #define SCE_PS_BADSTRINGCHAR 15 #define SCE_NSIS_DEFAULT 0 #define SCE_NSIS_COMMENT 1 #define SCE_NSIS_STRINGDQ 2 #define SCE_NSIS_STRINGLQ 3 #define SCE_NSIS_STRINGRQ 4 #define SCE_NSIS_FUNCTION 5 #define SCE_NSIS_VARIABLE 6 #define SCE_NSIS_LABEL 7 #define SCE_NSIS_USERDEFINED 8 #define SCE_NSIS_SECTIONDEF 9 #define SCE_NSIS_SUBSECTIONDEF 10 #define SCE_NSIS_IFDEFINEDEF 11 #define SCE_NSIS_MACRODEF 12 #define SCE_NSIS_STRINGVAR 13 #define SCE_NSIS_NUMBER 14 #define SCE_NSIS_SECTIONGROUP 15 #define SCE_NSIS_PAGEEX 16 #define SCE_NSIS_FUNCTIONDEF 17 #define SCE_NSIS_COMMENTBOX 18 #define SCE_MMIXAL_LEADWS 0 #define SCE_MMIXAL_COMMENT 1 #define SCE_MMIXAL_LABEL 2 #define SCE_MMIXAL_OPCODE 3 #define SCE_MMIXAL_OPCODE_PRE 4 #define SCE_MMIXAL_OPCODE_VALID 5 #define SCE_MMIXAL_OPCODE_UNKNOWN 6 #define SCE_MMIXAL_OPCODE_POST 7 #define SCE_MMIXAL_OPERANDS 8 #define SCE_MMIXAL_NUMBER 9 #define SCE_MMIXAL_REF 10 #define SCE_MMIXAL_CHAR 11 #define SCE_MMIXAL_STRING 12 #define SCE_MMIXAL_REGISTER 13 #define SCE_MMIXAL_HEX 14 #define SCE_MMIXAL_OPERATOR 15 #define SCE_MMIXAL_SYMBOL 16 #define SCE_MMIXAL_INCLUDE 17 #define SCE_CLW_DEFAULT 0 #define SCE_CLW_LABEL 1 #define SCE_CLW_COMMENT 2 #define SCE_CLW_STRING 3 #define SCE_CLW_USER_IDENTIFIER 4 #define SCE_CLW_INTEGER_CONSTANT 5 #define SCE_CLW_REAL_CONSTANT 6 #define SCE_CLW_PICTURE_STRING 7 #define SCE_CLW_KEYWORD 8 #define SCE_CLW_COMPILER_DIRECTIVE 9 #define SCE_CLW_RUNTIME_EXPRESSIONS 10 #define SCE_CLW_BUILTIN_PROCEDURES_FUNCTION 11 #define SCE_CLW_STRUCTURE_DATA_TYPE 12 #define SCE_CLW_ATTRIBUTE 13 #define SCE_CLW_STANDARD_EQUATE 14 #define SCE_CLW_ERROR 15 #define SCE_CLW_DEPRECATED 16 #define SCE_LOT_DEFAULT 0 #define SCE_LOT_HEADER 1 #define SCE_LOT_BREAK 2 #define SCE_LOT_SET 3 #define SCE_LOT_PASS 4 #define SCE_LOT_FAIL 5 #define SCE_LOT_ABORT 6 #define SCE_YAML_DEFAULT 0 #define SCE_YAML_COMMENT 1 #define SCE_YAML_IDENTIFIER 2 #define SCE_YAML_KEYWORD 3 #define SCE_YAML_NUMBER 4 #define SCE_YAML_REFERENCE 5 #define SCE_YAML_DOCUMENT 6 #define SCE_YAML_TEXT 7 #define SCE_YAML_ERROR 8 #define SCE_YAML_OPERATOR 9 #define SCE_TEX_DEFAULT 0 #define SCE_TEX_SPECIAL 1 #define SCE_TEX_GROUP 2 #define SCE_TEX_SYMBOL 3 #define SCE_TEX_COMMAND 4 #define SCE_TEX_TEXT 5 #define SCE_METAPOST_DEFAULT 0 #define SCE_METAPOST_SPECIAL 1 #define SCE_METAPOST_GROUP 2 #define SCE_METAPOST_SYMBOL 3 #define SCE_METAPOST_COMMAND 4 #define SCE_METAPOST_TEXT 5 #define SCE_METAPOST_EXTRA 6 #define SCE_ERLANG_DEFAULT 0 #define SCE_ERLANG_COMMENT 1 #define SCE_ERLANG_VARIABLE 2 #define SCE_ERLANG_NUMBER 3 #define SCE_ERLANG_KEYWORD 4 #define SCE_ERLANG_STRING 5 #define SCE_ERLANG_OPERATOR 6 #define SCE_ERLANG_ATOM 7 #define SCE_ERLANG_FUNCTION_NAME 8 #define SCE_ERLANG_CHARACTER 9 #define SCE_ERLANG_MACRO 10 #define SCE_ERLANG_RECORD 11 #define SCE_ERLANG_PREPROC 12 #define SCE_ERLANG_NODE_NAME 13 #define SCE_ERLANG_COMMENT_FUNCTION 14 #define SCE_ERLANG_COMMENT_MODULE 15 #define SCE_ERLANG_COMMENT_DOC 16 #define SCE_ERLANG_COMMENT_DOC_MACRO 17 #define SCE_ERLANG_ATOM_QUOTED 18 #define SCE_ERLANG_MACRO_QUOTED 19 #define SCE_ERLANG_RECORD_QUOTED 20 #define SCE_ERLANG_NODE_NAME_QUOTED 21 #define SCE_ERLANG_BIFS 22 #define SCE_ERLANG_MODULES 23 #define SCE_ERLANG_MODULES_ATT 24 #define SCE_ERLANG_UNKNOWN 31 #define SCE_MSSQL_DEFAULT 0 #define SCE_MSSQL_COMMENT 1 #define SCE_MSSQL_LINE_COMMENT 2 #define SCE_MSSQL_NUMBER 3 #define SCE_MSSQL_STRING 4 #define SCE_MSSQL_OPERATOR 5 #define SCE_MSSQL_IDENTIFIER 6 #define SCE_MSSQL_VARIABLE 7 #define SCE_MSSQL_COLUMN_NAME 8 #define SCE_MSSQL_STATEMENT 9 #define SCE_MSSQL_DATATYPE 10 #define SCE_MSSQL_SYSTABLE 11 #define SCE_MSSQL_GLOBAL_VARIABLE 12 #define SCE_MSSQL_FUNCTION 13 #define SCE_MSSQL_STORED_PROCEDURE 14 #define SCE_MSSQL_DEFAULT_PREF_DATATYPE 15 #define SCE_MSSQL_COLUMN_NAME_2 16 #define SCE_V_DEFAULT 0 #define SCE_V_COMMENT 1 #define SCE_V_COMMENTLINE 2 #define SCE_V_COMMENTLINEBANG 3 #define SCE_V_NUMBER 4 #define SCE_V_WORD 5 #define SCE_V_STRING 6 #define SCE_V_WORD2 7 #define SCE_V_WORD3 8 #define SCE_V_PREPROCESSOR 9 #define SCE_V_OPERATOR 10 #define SCE_V_IDENTIFIER 11 #define SCE_V_STRINGEOL 12 #define SCE_V_USER 19 #define SCE_KIX_DEFAULT 0 #define SCE_KIX_COMMENT 1 #define SCE_KIX_STRING1 2 #define SCE_KIX_STRING2 3 #define SCE_KIX_NUMBER 4 #define SCE_KIX_VAR 5 #define SCE_KIX_MACRO 6 #define SCE_KIX_KEYWORD 7 #define SCE_KIX_FUNCTIONS 8 #define SCE_KIX_OPERATOR 9 #define SCE_KIX_IDENTIFIER 31 #define SCE_GC_DEFAULT 0 #define SCE_GC_COMMENTLINE 1 #define SCE_GC_COMMENTBLOCK 2 #define SCE_GC_GLOBAL 3 #define SCE_GC_EVENT 4 #define SCE_GC_ATTRIBUTE 5 #define SCE_GC_CONTROL 6 #define SCE_GC_COMMAND 7 #define SCE_GC_STRING 8 #define SCE_GC_OPERATOR 9 #define SCE_SN_DEFAULT 0 #define SCE_SN_CODE 1 #define SCE_SN_COMMENTLINE 2 #define SCE_SN_COMMENTLINEBANG 3 #define SCE_SN_NUMBER 4 #define SCE_SN_WORD 5 #define SCE_SN_STRING 6 #define SCE_SN_WORD2 7 #define SCE_SN_WORD3 8 #define SCE_SN_PREPROCESSOR 9 #define SCE_SN_OPERATOR 10 #define SCE_SN_IDENTIFIER 11 #define SCE_SN_STRINGEOL 12 #define SCE_SN_REGEXTAG 13 #define SCE_SN_SIGNAL 14 #define SCE_SN_USER 19 #define SCE_AU3_DEFAULT 0 #define SCE_AU3_COMMENT 1 #define SCE_AU3_COMMENTBLOCK 2 #define SCE_AU3_NUMBER 3 #define SCE_AU3_FUNCTION 4 #define SCE_AU3_KEYWORD 5 #define SCE_AU3_MACRO 6 #define SCE_AU3_STRING 7 #define SCE_AU3_OPERATOR 8 #define SCE_AU3_VARIABLE 9 #define SCE_AU3_SENT 10 #define SCE_AU3_PREPROCESSOR 11 #define SCE_AU3_SPECIAL 12 #define SCE_AU3_EXPAND 13 #define SCE_AU3_COMOBJ 14 #define SCE_AU3_UDF 15 #define SCE_APDL_DEFAULT 0 #define SCE_APDL_COMMENT 1 #define SCE_APDL_COMMENTBLOCK 2 #define SCE_APDL_NUMBER 3 #define SCE_APDL_STRING 4 #define SCE_APDL_OPERATOR 5 #define SCE_APDL_WORD 6 #define SCE_APDL_PROCESSOR 7 #define SCE_APDL_COMMAND 8 #define SCE_APDL_SLASHCOMMAND 9 #define SCE_APDL_STARCOMMAND 10 #define SCE_APDL_ARGUMENT 11 #define SCE_APDL_FUNCTION 12 #define SCE_SH_DEFAULT 0 #define SCE_SH_ERROR 1 #define SCE_SH_COMMENTLINE 2 #define SCE_SH_NUMBER 3 #define SCE_SH_WORD 4 #define SCE_SH_STRING 5 #define SCE_SH_CHARACTER 6 #define SCE_SH_OPERATOR 7 #define SCE_SH_IDENTIFIER 8 #define SCE_SH_SCALAR 9 #define SCE_SH_PARAM 10 #define SCE_SH_BACKTICKS 11 #define SCE_SH_HERE_DELIM 12 #define SCE_SH_HERE_Q 13 #define SCE_ASN1_DEFAULT 0 #define SCE_ASN1_COMMENT 1 #define SCE_ASN1_IDENTIFIER 2 #define SCE_ASN1_STRING 3 #define SCE_ASN1_OID 4 #define SCE_ASN1_SCALAR 5 #define SCE_ASN1_KEYWORD 6 #define SCE_ASN1_ATTRIBUTE 7 #define SCE_ASN1_DESCRIPTOR 8 #define SCE_ASN1_TYPE 9 #define SCE_ASN1_OPERATOR 10 #define SCE_VHDL_DEFAULT 0 #define SCE_VHDL_COMMENT 1 #define SCE_VHDL_COMMENTLINEBANG 2 #define SCE_VHDL_NUMBER 3 #define SCE_VHDL_STRING 4 #define SCE_VHDL_OPERATOR 5 #define SCE_VHDL_IDENTIFIER 6 #define SCE_VHDL_STRINGEOL 7 #define SCE_VHDL_KEYWORD 8 #define SCE_VHDL_STDOPERATOR 9 #define SCE_VHDL_ATTRIBUTE 10 #define SCE_VHDL_STDFUNCTION 11 #define SCE_VHDL_STDPACKAGE 12 #define SCE_VHDL_STDTYPE 13 #define SCE_VHDL_USERWORD 14 #define SCE_CAML_DEFAULT 0 #define SCE_CAML_IDENTIFIER 1 #define SCE_CAML_TAGNAME 2 #define SCE_CAML_KEYWORD 3 #define SCE_CAML_KEYWORD2 4 #define SCE_CAML_KEYWORD3 5 #define SCE_CAML_LINENUM 6 #define SCE_CAML_OPERATOR 7 #define SCE_CAML_NUMBER 8 #define SCE_CAML_CHAR 9 #define SCE_CAML_WHITE 10 #define SCE_CAML_STRING 11 #define SCE_CAML_COMMENT 12 #define SCE_CAML_COMMENT1 13 #define SCE_CAML_COMMENT2 14 #define SCE_CAML_COMMENT3 15 #define SCE_HA_DEFAULT 0 #define SCE_HA_IDENTIFIER 1 #define SCE_HA_KEYWORD 2 #define SCE_HA_NUMBER 3 #define SCE_HA_STRING 4 #define SCE_HA_CHARACTER 5 #define SCE_HA_CLASS 6 #define SCE_HA_MODULE 7 #define SCE_HA_CAPITAL 8 #define SCE_HA_DATA 9 #define SCE_HA_IMPORT 10 #define SCE_HA_OPERATOR 11 #define SCE_HA_INSTANCE 12 #define SCE_HA_COMMENTLINE 13 #define SCE_HA_COMMENTBLOCK 14 #define SCE_HA_COMMENTBLOCK2 15 #define SCE_HA_COMMENTBLOCK3 16 #define SCE_HA_PRAGMA 17 #define SCE_HA_PREPROCESSOR 18 #define SCE_HA_STRINGEOL 19 #define SCE_HA_RESERVED_OPERATOR 20 #define SCE_HA_LITERATE_COMMENT 21 #define SCE_HA_LITERATE_CODEDELIM 22 #define SCE_T3_DEFAULT 0 #define SCE_T3_X_DEFAULT 1 #define SCE_T3_PREPROCESSOR 2 #define SCE_T3_BLOCK_COMMENT 3 #define SCE_T3_LINE_COMMENT 4 #define SCE_T3_OPERATOR 5 #define SCE_T3_KEYWORD 6 #define SCE_T3_NUMBER 7 #define SCE_T3_IDENTIFIER 8 #define SCE_T3_S_STRING 9 #define SCE_T3_D_STRING 10 #define SCE_T3_X_STRING 11 #define SCE_T3_LIB_DIRECTIVE 12 #define SCE_T3_MSG_PARAM 13 #define SCE_T3_HTML_TAG 14 #define SCE_T3_HTML_DEFAULT 15 #define SCE_T3_HTML_STRING 16 #define SCE_T3_USER1 17 #define SCE_T3_USER2 18 #define SCE_T3_USER3 19 #define SCE_T3_BRACE 20 #define SCE_REBOL_DEFAULT 0 #define SCE_REBOL_COMMENTLINE 1 #define SCE_REBOL_COMMENTBLOCK 2 #define SCE_REBOL_PREFACE 3 #define SCE_REBOL_OPERATOR 4 #define SCE_REBOL_CHARACTER 5 #define SCE_REBOL_QUOTEDSTRING 6 #define SCE_REBOL_BRACEDSTRING 7 #define SCE_REBOL_NUMBER 8 #define SCE_REBOL_PAIR 9 #define SCE_REBOL_TUPLE 10 #define SCE_REBOL_BINARY 11 #define SCE_REBOL_MONEY 12 #define SCE_REBOL_ISSUE 13 #define SCE_REBOL_TAG 14 #define SCE_REBOL_FILE 15 #define SCE_REBOL_EMAIL 16 #define SCE_REBOL_URL 17 #define SCE_REBOL_DATE 18 #define SCE_REBOL_TIME 19 #define SCE_REBOL_IDENTIFIER 20 #define SCE_REBOL_WORD 21 #define SCE_REBOL_WORD2 22 #define SCE_REBOL_WORD3 23 #define SCE_REBOL_WORD4 24 #define SCE_REBOL_WORD5 25 #define SCE_REBOL_WORD6 26 #define SCE_REBOL_WORD7 27 #define SCE_REBOL_WORD8 28 #define SCE_SQL_DEFAULT 0 #define SCE_SQL_COMMENT 1 #define SCE_SQL_COMMENTLINE 2 #define SCE_SQL_COMMENTDOC 3 #define SCE_SQL_NUMBER 4 #define SCE_SQL_WORD 5 #define SCE_SQL_STRING 6 #define SCE_SQL_CHARACTER 7 #define SCE_SQL_SQLPLUS 8 #define SCE_SQL_SQLPLUS_PROMPT 9 #define SCE_SQL_OPERATOR 10 #define SCE_SQL_IDENTIFIER 11 #define SCE_SQL_SQLPLUS_COMMENT 13 #define SCE_SQL_COMMENTLINEDOC 15 #define SCE_SQL_WORD2 16 #define SCE_SQL_COMMENTDOCKEYWORD 17 #define SCE_SQL_COMMENTDOCKEYWORDERROR 18 #define SCE_SQL_USER1 19 #define SCE_SQL_USER2 20 #define SCE_SQL_USER3 21 #define SCE_SQL_USER4 22 #define SCE_SQL_QUOTEDIDENTIFIER 23 #define SCE_ST_DEFAULT 0 #define SCE_ST_STRING 1 #define SCE_ST_NUMBER 2 #define SCE_ST_COMMENT 3 #define SCE_ST_SYMBOL 4 #define SCE_ST_BINARY 5 #define SCE_ST_BOOL 6 #define SCE_ST_SELF 7 #define SCE_ST_SUPER 8 #define SCE_ST_NIL 9 #define SCE_ST_GLOBAL 10 #define SCE_ST_RETURN 11 #define SCE_ST_SPECIAL 12 #define SCE_ST_KWSEND 13 #define SCE_ST_ASSIGN 14 #define SCE_ST_CHARACTER 15 #define SCE_ST_SPEC_SEL 16 #define SCE_FS_DEFAULT 0 #define SCE_FS_COMMENT 1 #define SCE_FS_COMMENTLINE 2 #define SCE_FS_COMMENTDOC 3 #define SCE_FS_COMMENTLINEDOC 4 #define SCE_FS_COMMENTDOCKEYWORD 5 #define SCE_FS_COMMENTDOCKEYWORDERROR 6 #define SCE_FS_KEYWORD 7 #define SCE_FS_KEYWORD2 8 #define SCE_FS_KEYWORD3 9 #define SCE_FS_KEYWORD4 10 #define SCE_FS_NUMBER 11 #define SCE_FS_STRING 12 #define SCE_FS_PREPROCESSOR 13 #define SCE_FS_OPERATOR 14 #define SCE_FS_IDENTIFIER 15 #define SCE_FS_DATE 16 #define SCE_FS_STRINGEOL 17 #define SCE_FS_CONSTANT 18 #define SCE_FS_WORDOPERATOR 19 #define SCE_FS_DISABLEDCODE 20 #define SCE_FS_DEFAULT_C 21 #define SCE_FS_COMMENTDOC_C 22 #define SCE_FS_COMMENTLINEDOC_C 23 #define SCE_FS_KEYWORD_C 24 #define SCE_FS_KEYWORD2_C 25 #define SCE_FS_NUMBER_C 26 #define SCE_FS_STRING_C 27 #define SCE_FS_PREPROCESSOR_C 28 #define SCE_FS_OPERATOR_C 29 #define SCE_FS_IDENTIFIER_C 30 #define SCE_FS_STRINGEOL_C 31 #define SCE_CSOUND_DEFAULT 0 #define SCE_CSOUND_COMMENT 1 #define SCE_CSOUND_NUMBER 2 #define SCE_CSOUND_OPERATOR 3 #define SCE_CSOUND_INSTR 4 #define SCE_CSOUND_IDENTIFIER 5 #define SCE_CSOUND_OPCODE 6 #define SCE_CSOUND_HEADERSTMT 7 #define SCE_CSOUND_USERKEYWORD 8 #define SCE_CSOUND_COMMENTBLOCK 9 #define SCE_CSOUND_PARAM 10 #define SCE_CSOUND_ARATE_VAR 11 #define SCE_CSOUND_KRATE_VAR 12 #define SCE_CSOUND_IRATE_VAR 13 #define SCE_CSOUND_GLOBAL_VAR 14 #define SCE_CSOUND_STRINGEOL 15 #define SCE_INNO_DEFAULT 0 #define SCE_INNO_COMMENT 1 #define SCE_INNO_KEYWORD 2 #define SCE_INNO_PARAMETER 3 #define SCE_INNO_SECTION 4 #define SCE_INNO_PREPROC 5 #define SCE_INNO_INLINE_EXPANSION 6 #define SCE_INNO_COMMENT_PASCAL 7 #define SCE_INNO_KEYWORD_PASCAL 8 #define SCE_INNO_KEYWORD_USER 9 #define SCE_INNO_STRING_DOUBLE 10 #define SCE_INNO_STRING_SINGLE 11 #define SCE_INNO_IDENTIFIER 12 #define SCE_OPAL_SPACE 0 #define SCE_OPAL_COMMENT_BLOCK 1 #define SCE_OPAL_COMMENT_LINE 2 #define SCE_OPAL_INTEGER 3 #define SCE_OPAL_KEYWORD 4 #define SCE_OPAL_SORT 5 #define SCE_OPAL_STRING 6 #define SCE_OPAL_PAR 7 #define SCE_OPAL_BOOL_CONST 8 #define SCE_OPAL_DEFAULT 32 #define SCE_SPICE_DEFAULT 0 #define SCE_SPICE_IDENTIFIER 1 #define SCE_SPICE_KEYWORD 2 #define SCE_SPICE_KEYWORD2 3 #define SCE_SPICE_KEYWORD3 4 #define SCE_SPICE_NUMBER 5 #define SCE_SPICE_DELIMITER 6 #define SCE_SPICE_VALUE 7 #define SCE_SPICE_COMMENTLINE 8 #define SCE_CMAKE_DEFAULT 0 #define SCE_CMAKE_COMMENT 1 #define SCE_CMAKE_STRINGDQ 2 #define SCE_CMAKE_STRINGLQ 3 #define SCE_CMAKE_STRINGRQ 4 #define SCE_CMAKE_COMMANDS 5 #define SCE_CMAKE_PARAMETERS 6 #define SCE_CMAKE_VARIABLE 7 #define SCE_CMAKE_USERDEFINED 8 #define SCE_CMAKE_WHILEDEF 9 #define SCE_CMAKE_FOREACHDEF 10 #define SCE_CMAKE_IFDEFINEDEF 11 #define SCE_CMAKE_MACRODEF 12 #define SCE_CMAKE_STRINGVAR 13 #define SCE_CMAKE_NUMBER 14 #define SCE_GAP_DEFAULT 0 #define SCE_GAP_IDENTIFIER 1 #define SCE_GAP_KEYWORD 2 #define SCE_GAP_KEYWORD2 3 #define SCE_GAP_KEYWORD3 4 #define SCE_GAP_KEYWORD4 5 #define SCE_GAP_STRING 6 #define SCE_GAP_CHAR 7 #define SCE_GAP_OPERATOR 8 #define SCE_GAP_COMMENT 9 #define SCE_GAP_NUMBER 10 #define SCE_GAP_STRINGEOL 11 #define SCE_PLM_DEFAULT 0 #define SCE_PLM_COMMENT 1 #define SCE_PLM_STRING 2 #define SCE_PLM_NUMBER 3 #define SCE_PLM_IDENTIFIER 4 #define SCE_PLM_OPERATOR 5 #define SCE_PLM_CONTROL 6 #define SCE_PLM_KEYWORD 7 #define SCE_4GL_DEFAULT 0 #define SCE_4GL_NUMBER 1 #define SCE_4GL_WORD 2 #define SCE_4GL_STRING 3 #define SCE_4GL_CHARACTER 4 #define SCE_4GL_PREPROCESSOR 5 #define SCE_4GL_OPERATOR 6 #define SCE_4GL_IDENTIFIER 7 #define SCE_4GL_BLOCK 8 #define SCE_4GL_END 9 #define SCE_4GL_COMMENT1 10 #define SCE_4GL_COMMENT2 11 #define SCE_4GL_COMMENT3 12 #define SCE_4GL_COMMENT4 13 #define SCE_4GL_COMMENT5 14 #define SCE_4GL_COMMENT6 15 #define SCE_4GL_DEFAULT_ 16 #define SCE_4GL_NUMBER_ 17 #define SCE_4GL_WORD_ 18 #define SCE_4GL_STRING_ 19 #define SCE_4GL_CHARACTER_ 20 #define SCE_4GL_PREPROCESSOR_ 21 #define SCE_4GL_OPERATOR_ 22 #define SCE_4GL_IDENTIFIER_ 23 #define SCE_4GL_BLOCK_ 24 #define SCE_4GL_END_ 25 #define SCE_4GL_COMMENT1_ 26 #define SCE_4GL_COMMENT2_ 27 #define SCE_4GL_COMMENT3_ 28 #define SCE_4GL_COMMENT4_ 29 #define SCE_4GL_COMMENT5_ 30 #define SCE_4GL_COMMENT6_ 31 #define SCE_ABAQUS_DEFAULT 0 #define SCE_ABAQUS_COMMENT 1 #define SCE_ABAQUS_COMMENTBLOCK 2 #define SCE_ABAQUS_NUMBER 3 #define SCE_ABAQUS_STRING 4 #define SCE_ABAQUS_OPERATOR 5 #define SCE_ABAQUS_WORD 6 #define SCE_ABAQUS_PROCESSOR 7 #define SCE_ABAQUS_COMMAND 8 #define SCE_ABAQUS_SLASHCOMMAND 9 #define SCE_ABAQUS_STARCOMMAND 10 #define SCE_ABAQUS_ARGUMENT 11 #define SCE_ABAQUS_FUNCTION 12 #define SCE_ASY_DEFAULT 0 #define SCE_ASY_COMMENT 1 #define SCE_ASY_COMMENTLINE 2 #define SCE_ASY_NUMBER 3 #define SCE_ASY_WORD 4 #define SCE_ASY_STRING 5 #define SCE_ASY_CHARACTER 6 #define SCE_ASY_OPERATOR 7 #define SCE_ASY_IDENTIFIER 8 #define SCE_ASY_STRINGEOL 9 #define SCE_ASY_COMMENTLINEDOC 10 #define SCE_ASY_WORD2 11 #define SCE_R_DEFAULT 0 #define SCE_R_COMMENT 1 #define SCE_R_KWORD 2 #define SCE_R_BASEKWORD 3 #define SCE_R_OTHERKWORD 4 #define SCE_R_NUMBER 5 #define SCE_R_STRING 6 #define SCE_R_STRING2 7 #define SCE_R_OPERATOR 8 #define SCE_R_IDENTIFIER 9 #define SCE_R_INFIX 10 #define SCE_R_INFIXEOL 11 #define SCE_MAGIK_DEFAULT 0 #define SCE_MAGIK_COMMENT 1 #define SCE_MAGIK_HYPER_COMMENT 16 #define SCE_MAGIK_STRING 2 #define SCE_MAGIK_CHARACTER 3 #define SCE_MAGIK_NUMBER 4 #define SCE_MAGIK_IDENTIFIER 5 #define SCE_MAGIK_OPERATOR 6 #define SCE_MAGIK_FLOW 7 #define SCE_MAGIK_CONTAINER 8 #define SCE_MAGIK_BRACKET_BLOCK 9 #define SCE_MAGIK_BRACE_BLOCK 10 #define SCE_MAGIK_SQBRACKET_BLOCK 11 #define SCE_MAGIK_UNKNOWN_KEYWORD 12 #define SCE_MAGIK_KEYWORD 13 #define SCE_MAGIK_PRAGMA 14 #define SCE_MAGIK_SYMBOL 15 #define SCE_POWERSHELL_DEFAULT 0 #define SCE_POWERSHELL_COMMENT 1 #define SCE_POWERSHELL_STRING 2 #define SCE_POWERSHELL_CHARACTER 3 #define SCE_POWERSHELL_NUMBER 4 #define SCE_POWERSHELL_VARIABLE 5 #define SCE_POWERSHELL_OPERATOR 6 #define SCE_POWERSHELL_IDENTIFIER 7 #define SCE_POWERSHELL_KEYWORD 8 #define SCE_POWERSHELL_CMDLET 9 #define SCE_POWERSHELL_ALIAS 10 #define SCE_POWERSHELL_FUNCTION 11 #define SCE_POWERSHELL_USER1 12 #define SCE_POWERSHELL_COMMENTSTREAM 13 #define SCE_POWERSHELL_HERE_STRING 14 #define SCE_POWERSHELL_HERE_CHARACTER 15 #define SCE_POWERSHELL_COMMENTDOCKEYWORD 16 #define SCE_MYSQL_DEFAULT 0 #define SCE_MYSQL_COMMENT 1 #define SCE_MYSQL_COMMENTLINE 2 #define SCE_MYSQL_VARIABLE 3 #define SCE_MYSQL_SYSTEMVARIABLE 4 #define SCE_MYSQL_KNOWNSYSTEMVARIABLE 5 #define SCE_MYSQL_NUMBER 6 #define SCE_MYSQL_MAJORKEYWORD 7 #define SCE_MYSQL_KEYWORD 8 #define SCE_MYSQL_DATABASEOBJECT 9 #define SCE_MYSQL_PROCEDUREKEYWORD 10 #define SCE_MYSQL_STRING 11 #define SCE_MYSQL_SQSTRING 12 #define SCE_MYSQL_DQSTRING 13 #define SCE_MYSQL_OPERATOR 14 #define SCE_MYSQL_FUNCTION 15 #define SCE_MYSQL_IDENTIFIER 16 #define SCE_MYSQL_QUOTEDIDENTIFIER 17 #define SCE_MYSQL_USER1 18 #define SCE_MYSQL_USER2 19 #define SCE_MYSQL_USER3 20 #define SCE_MYSQL_HIDDENCOMMAND 21 #define SCE_MYSQL_PLACEHOLDER 22 #define SCE_PO_DEFAULT 0 #define SCE_PO_COMMENT 1 #define SCE_PO_MSGID 2 #define SCE_PO_MSGID_TEXT 3 #define SCE_PO_MSGSTR 4 #define SCE_PO_MSGSTR_TEXT 5 #define SCE_PO_MSGCTXT 6 #define SCE_PO_MSGCTXT_TEXT 7 #define SCE_PO_FUZZY 8 #define SCE_PO_PROGRAMMER_COMMENT 9 #define SCE_PO_REFERENCE 10 #define SCE_PO_FLAGS 11 #define SCE_PO_MSGID_TEXT_EOL 12 #define SCE_PO_MSGSTR_TEXT_EOL 13 #define SCE_PO_MSGCTXT_TEXT_EOL 14 #define SCE_PO_ERROR 15 #define SCE_PAS_DEFAULT 0 #define SCE_PAS_IDENTIFIER 1 #define SCE_PAS_COMMENT 2 #define SCE_PAS_COMMENT2 3 #define SCE_PAS_COMMENTLINE 4 #define SCE_PAS_PREPROCESSOR 5 #define SCE_PAS_PREPROCESSOR2 6 #define SCE_PAS_NUMBER 7 #define SCE_PAS_HEXNUMBER 8 #define SCE_PAS_WORD 9 #define SCE_PAS_STRING 10 #define SCE_PAS_STRINGEOL 11 #define SCE_PAS_CHARACTER 12 #define SCE_PAS_OPERATOR 13 #define SCE_PAS_ASM 14 #define SCE_SORCUS_DEFAULT 0 #define SCE_SORCUS_COMMAND 1 #define SCE_SORCUS_PARAMETER 2 #define SCE_SORCUS_COMMENTLINE 3 #define SCE_SORCUS_STRING 4 #define SCE_SORCUS_STRINGEOL 5 #define SCE_SORCUS_IDENTIFIER 6 #define SCE_SORCUS_OPERATOR 7 #define SCE_SORCUS_NUMBER 8 #define SCE_SORCUS_CONSTANT 9 #define SCE_POWERPRO_DEFAULT 0 #define SCE_POWERPRO_COMMENTBLOCK 1 #define SCE_POWERPRO_COMMENTLINE 2 #define SCE_POWERPRO_NUMBER 3 #define SCE_POWERPRO_WORD 4 #define SCE_POWERPRO_WORD2 5 #define SCE_POWERPRO_WORD3 6 #define SCE_POWERPRO_WORD4 7 #define SCE_POWERPRO_DOUBLEQUOTEDSTRING 8 #define SCE_POWERPRO_SINGLEQUOTEDSTRING 9 #define SCE_POWERPRO_LINECONTINUE 10 #define SCE_POWERPRO_OPERATOR 11 #define SCE_POWERPRO_IDENTIFIER 12 #define SCE_POWERPRO_STRINGEOL 13 #define SCE_POWERPRO_VERBATIM 14 #define SCE_POWERPRO_ALTQUOTE 15 #define SCE_POWERPRO_FUNCTION 16 #define SCE_SML_DEFAULT 0 #define SCE_SML_IDENTIFIER 1 #define SCE_SML_TAGNAME 2 #define SCE_SML_KEYWORD 3 #define SCE_SML_KEYWORD2 4 #define SCE_SML_KEYWORD3 5 #define SCE_SML_LINENUM 6 #define SCE_SML_OPERATOR 7 #define SCE_SML_NUMBER 8 #define SCE_SML_CHAR 9 #define SCE_SML_STRING 11 #define SCE_SML_COMMENT 12 #define SCE_SML_COMMENT1 13 #define SCE_SML_COMMENT2 14 #define SCE_SML_COMMENT3 15 #define SCE_MARKDOWN_DEFAULT 0 #define SCE_MARKDOWN_LINE_BEGIN 1 #define SCE_MARKDOWN_STRONG1 2 #define SCE_MARKDOWN_STRONG2 3 #define SCE_MARKDOWN_EM1 4 #define SCE_MARKDOWN_EM2 5 #define SCE_MARKDOWN_HEADER1 6 #define SCE_MARKDOWN_HEADER2 7 #define SCE_MARKDOWN_HEADER3 8 #define SCE_MARKDOWN_HEADER4 9 #define SCE_MARKDOWN_HEADER5 10 #define SCE_MARKDOWN_HEADER6 11 #define SCE_MARKDOWN_PRECHAR 12 #define SCE_MARKDOWN_ULIST_ITEM 13 #define SCE_MARKDOWN_OLIST_ITEM 14 #define SCE_MARKDOWN_BLOCKQUOTE 15 #define SCE_MARKDOWN_STRIKEOUT 16 #define SCE_MARKDOWN_HRULE 17 #define SCE_MARKDOWN_LINK 18 #define SCE_MARKDOWN_CODE 19 #define SCE_MARKDOWN_CODE2 20 #define SCE_MARKDOWN_CODEBK 21 #define SCE_TXT2TAGS_DEFAULT 0 #define SCE_TXT2TAGS_LINE_BEGIN 1 #define SCE_TXT2TAGS_STRONG1 2 #define SCE_TXT2TAGS_STRONG2 3 #define SCE_TXT2TAGS_EM1 4 #define SCE_TXT2TAGS_EM2 5 #define SCE_TXT2TAGS_HEADER1 6 #define SCE_TXT2TAGS_HEADER2 7 #define SCE_TXT2TAGS_HEADER3 8 #define SCE_TXT2TAGS_HEADER4 9 #define SCE_TXT2TAGS_HEADER5 10 #define SCE_TXT2TAGS_HEADER6 11 #define SCE_TXT2TAGS_PRECHAR 12 #define SCE_TXT2TAGS_ULIST_ITEM 13 #define SCE_TXT2TAGS_OLIST_ITEM 14 #define SCE_TXT2TAGS_BLOCKQUOTE 15 #define SCE_TXT2TAGS_STRIKEOUT 16 #define SCE_TXT2TAGS_HRULE 17 #define SCE_TXT2TAGS_LINK 18 #define SCE_TXT2TAGS_CODE 19 #define SCE_TXT2TAGS_CODE2 20 #define SCE_TXT2TAGS_CODEBK 21 #define SCE_TXT2TAGS_COMMENT 22 #define SCE_TXT2TAGS_OPTION 23 #define SCE_TXT2TAGS_PREPROC 24 #define SCE_TXT2TAGS_POSTPROC 25 #define SCE_A68K_DEFAULT 0 #define SCE_A68K_COMMENT 1 #define SCE_A68K_NUMBER_DEC 2 #define SCE_A68K_NUMBER_BIN 3 #define SCE_A68K_NUMBER_HEX 4 #define SCE_A68K_STRING1 5 #define SCE_A68K_OPERATOR 6 #define SCE_A68K_CPUINSTRUCTION 7 #define SCE_A68K_EXTINSTRUCTION 8 #define SCE_A68K_REGISTER 9 #define SCE_A68K_DIRECTIVE 10 #define SCE_A68K_MACRO_ARG 11 #define SCE_A68K_LABEL 12 #define SCE_A68K_STRING2 13 #define SCE_A68K_IDENTIFIER 14 #define SCE_A68K_MACRO_DECLARATION 15 #define SCE_A68K_COMMENT_WORD 16 #define SCE_A68K_COMMENT_SPECIAL 17 #define SCE_A68K_COMMENT_DOXYGEN 18 #define SCE_MODULA_DEFAULT 0 #define SCE_MODULA_COMMENT 1 #define SCE_MODULA_DOXYCOMM 2 #define SCE_MODULA_DOXYKEY 3 #define SCE_MODULA_KEYWORD 4 #define SCE_MODULA_RESERVED 5 #define SCE_MODULA_NUMBER 6 #define SCE_MODULA_BASENUM 7 #define SCE_MODULA_FLOAT 8 #define SCE_MODULA_STRING 9 #define SCE_MODULA_STRSPEC 10 #define SCE_MODULA_CHAR 11 #define SCE_MODULA_CHARSPEC 12 #define SCE_MODULA_PROC 13 #define SCE_MODULA_PRAGMA 14 #define SCE_MODULA_PRGKEY 15 #define SCE_MODULA_OPERATOR 16 #define SCE_MODULA_BADSTR 17 #define SCE_COFFEESCRIPT_DEFAULT 0 #define SCE_COFFEESCRIPT_COMMENT 1 #define SCE_COFFEESCRIPT_COMMENTLINE 2 #define SCE_COFFEESCRIPT_COMMENTDOC 3 #define SCE_COFFEESCRIPT_NUMBER 4 #define SCE_COFFEESCRIPT_WORD 5 #define SCE_COFFEESCRIPT_STRING 6 #define SCE_COFFEESCRIPT_CHARACTER 7 #define SCE_COFFEESCRIPT_UUID 8 #define SCE_COFFEESCRIPT_PREPROCESSOR 9 #define SCE_COFFEESCRIPT_OPERATOR 10 #define SCE_COFFEESCRIPT_IDENTIFIER 11 #define SCE_COFFEESCRIPT_STRINGEOL 12 #define SCE_COFFEESCRIPT_VERBATIM 13 #define SCE_COFFEESCRIPT_REGEX 14 #define SCE_COFFEESCRIPT_COMMENTLINEDOC 15 #define SCE_COFFEESCRIPT_WORD2 16 #define SCE_COFFEESCRIPT_COMMENTDOCKEYWORD 17 #define SCE_COFFEESCRIPT_COMMENTDOCKEYWORDERROR 18 #define SCE_COFFEESCRIPT_GLOBALCLASS 19 #define SCE_COFFEESCRIPT_STRINGRAW 20 #define SCE_COFFEESCRIPT_TRIPLEVERBATIM 21 #define SCE_COFFEESCRIPT_HASHQUOTEDSTRING 22 #define SCE_COFFEESCRIPT_COMMENTBLOCK 22 #define SCE_COFFEESCRIPT_VERBOSE_REGEX 23 #define SCE_COFFEESCRIPT_VERBOSE_REGEX_COMMENT 24 #define SCE_AVS_DEFAULT 0 #define SCE_AVS_COMMENTBLOCK 1 #define SCE_AVS_COMMENTBLOCKN 2 #define SCE_AVS_COMMENTLINE 3 #define SCE_AVS_NUMBER 4 #define SCE_AVS_OPERATOR 5 #define SCE_AVS_IDENTIFIER 6 #define SCE_AVS_STRING 7 #define SCE_AVS_TRIPLESTRING 8 #define SCE_AVS_KEYWORD 9 #define SCE_AVS_FILTER 10 #define SCE_AVS_PLUGIN 11 #define SCE_AVS_FUNCTION 12 #define SCE_AVS_CLIPPROP 13 #define SCE_AVS_USERDFN 14 #define SCE_ECL_DEFAULT 0 #define SCE_ECL_COMMENT 1 #define SCE_ECL_COMMENTLINE 2 #define SCE_ECL_NUMBER 3 #define SCE_ECL_STRING 4 #define SCE_ECL_WORD0 5 #define SCE_ECL_OPERATOR 6 #define SCE_ECL_CHARACTER 7 #define SCE_ECL_UUID 8 #define SCE_ECL_PREPROCESSOR 9 #define SCE_ECL_UNKNOWN 10 #define SCE_ECL_IDENTIFIER 11 #define SCE_ECL_STRINGEOL 12 #define SCE_ECL_VERBATIM 13 #define SCE_ECL_REGEX 14 #define SCE_ECL_COMMENTLINEDOC 15 #define SCE_ECL_WORD1 16 #define SCE_ECL_COMMENTDOCKEYWORD 17 #define SCE_ECL_COMMENTDOCKEYWORDERROR 18 #define SCE_ECL_WORD2 19 #define SCE_ECL_WORD3 20 #define SCE_ECL_WORD4 21 #define SCE_ECL_WORD5 22 #define SCE_ECL_COMMENTDOC 23 #define SCE_ECL_ADDED 24 #define SCE_ECL_DELETED 25 #define SCE_ECL_CHANGED 26 #define SCE_ECL_MOVED 27 #define SCE_OSCRIPT_DEFAULT 0 #define SCE_OSCRIPT_LINE_COMMENT 1 #define SCE_OSCRIPT_BLOCK_COMMENT 2 #define SCE_OSCRIPT_DOC_COMMENT 3 #define SCE_OSCRIPT_PREPROCESSOR 4 #define SCE_OSCRIPT_NUMBER 5 #define SCE_OSCRIPT_SINGLEQUOTE_STRING 6 #define SCE_OSCRIPT_DOUBLEQUOTE_STRING 7 #define SCE_OSCRIPT_CONSTANT 8 #define SCE_OSCRIPT_IDENTIFIER 9 #define SCE_OSCRIPT_GLOBAL 10 #define SCE_OSCRIPT_KEYWORD 11 #define SCE_OSCRIPT_OPERATOR 12 #define SCE_OSCRIPT_LABEL 13 #define SCE_OSCRIPT_TYPE 14 #define SCE_OSCRIPT_FUNCTION 15 #define SCE_OSCRIPT_OBJECT 16 #define SCE_OSCRIPT_PROPERTY 17 #define SCE_OSCRIPT_METHOD 18 #define SCE_VISUALPROLOG_DEFAULT 0 #define SCE_VISUALPROLOG_KEY_MAJOR 1 #define SCE_VISUALPROLOG_KEY_MINOR 2 #define SCE_VISUALPROLOG_KEY_DIRECTIVE 3 #define SCE_VISUALPROLOG_COMMENT_BLOCK 4 #define SCE_VISUALPROLOG_COMMENT_LINE 5 #define SCE_VISUALPROLOG_COMMENT_KEY 6 #define SCE_VISUALPROLOG_COMMENT_KEY_ERROR 7 #define SCE_VISUALPROLOG_IDENTIFIER 8 #define SCE_VISUALPROLOG_VARIABLE 9 #define SCE_VISUALPROLOG_ANONYMOUS 10 #define SCE_VISUALPROLOG_NUMBER 11 #define SCE_VISUALPROLOG_OPERATOR 12 #define SCE_VISUALPROLOG_CHARACTER 13 #define SCE_VISUALPROLOG_CHARACTER_TOO_MANY 14 #define SCE_VISUALPROLOG_CHARACTER_ESCAPE_ERROR 15 #define SCE_VISUALPROLOG_STRING 16 #define SCE_VISUALPROLOG_STRING_ESCAPE 17 #define SCE_VISUALPROLOG_STRING_ESCAPE_ERROR 18 #define SCE_VISUALPROLOG_STRING_EOL_OPEN 19 #define SCE_VISUALPROLOG_STRING_VERBATIM 20 #define SCE_VISUALPROLOG_STRING_VERBATIM_SPECIAL 21 #define SCE_VISUALPROLOG_STRING_VERBATIM_EOL 22 #define SCE_STTXT_DEFAULT 0 #define SCE_STTXT_COMMENT 1 #define SCE_STTXT_COMMENTLINE 2 #define SCE_STTXT_KEYWORD 3 #define SCE_STTXT_TYPE 4 #define SCE_STTXT_FUNCTION 5 #define SCE_STTXT_FB 6 #define SCE_STTXT_NUMBER 7 #define SCE_STTXT_HEXNUMBER 8 #define SCE_STTXT_PRAGMA 9 #define SCE_STTXT_OPERATOR 10 #define SCE_STTXT_CHARACTER 11 #define SCE_STTXT_STRING1 12 #define SCE_STTXT_STRING2 13 #define SCE_STTXT_STRINGEOL 14 #define SCE_STTXT_IDENTIFIER 15 #define SCE_STTXT_DATETIME 16 #define SCE_STTXT_VARS 17 #define SCE_STTXT_PRAGMAS 18 #define SCE_KVIRC_DEFAULT 0 #define SCE_KVIRC_COMMENT 1 #define SCE_KVIRC_COMMENTBLOCK 2 #define SCE_KVIRC_STRING 3 #define SCE_KVIRC_WORD 4 #define SCE_KVIRC_KEYWORD 5 #define SCE_KVIRC_FUNCTION_KEYWORD 6 #define SCE_KVIRC_FUNCTION 7 #define SCE_KVIRC_VARIABLE 8 #define SCE_KVIRC_NUMBER 9 #define SCE_KVIRC_OPERATOR 10 #define SCE_KVIRC_STRING_FUNCTION 11 #define SCE_KVIRC_STRING_VARIABLE 12 #define SCE_RUST_DEFAULT 0 #define SCE_RUST_COMMENTBLOCK 1 #define SCE_RUST_COMMENTLINE 2 #define SCE_RUST_COMMENTBLOCKDOC 3 #define SCE_RUST_COMMENTLINEDOC 4 #define SCE_RUST_NUMBER 5 #define SCE_RUST_WORD 6 #define SCE_RUST_WORD2 7 #define SCE_RUST_WORD3 8 #define SCE_RUST_WORD4 9 #define SCE_RUST_WORD5 10 #define SCE_RUST_WORD6 11 #define SCE_RUST_WORD7 12 #define SCE_RUST_STRING 13 #define SCE_RUST_STRINGR 14 #define SCE_RUST_CHARACTER 15 #define SCE_RUST_OPERATOR 16 #define SCE_RUST_IDENTIFIER 17 #define SCE_RUST_LIFETIME 18 #define SCE_RUST_MACRO 19 #define SCE_RUST_LEXERROR 20 /* --Autogenerated -- end of section automatically generated from Scintilla.iface */ #endif
48,042
C++
.h
1,683
27.540107
97
0.813565
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,295
ScintillaWidget.h
Studio3T_robomongo/src/third-party/qscintilla-2.8.4/sources/include/ScintillaWidget.h
/* Scintilla source code edit control */ /** @file ScintillaWidget.h ** Definition of Scintilla widget for GTK+. ** Only needed by GTK+ code but is harmless on other platforms. **/ /* Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> * The License.txt file describes the conditions under which this software may be distributed. */ #ifndef SCINTILLAWIDGET_H #define SCINTILLAWIDGET_H #if defined(GTK) #ifdef __cplusplus extern "C" { #endif #define SCINTILLA(obj) G_TYPE_CHECK_INSTANCE_CAST (obj, scintilla_get_type (), ScintillaObject) #define SCINTILLA_CLASS(klass) G_TYPE_CHECK_CLASS_CAST (klass, scintilla_get_type (), ScintillaClass) #define IS_SCINTILLA(obj) G_TYPE_CHECK_INSTANCE_TYPE (obj, scintilla_get_type ()) typedef struct _ScintillaObject ScintillaObject; typedef struct _ScintillaClass ScintillaClass; struct _ScintillaObject { GtkContainer cont; void *pscin; }; struct _ScintillaClass { GtkContainerClass parent_class; void (* command) (ScintillaObject *ttt); void (* notify) (ScintillaObject *ttt); }; GType scintilla_get_type (void); GtkWidget* scintilla_new (void); void scintilla_set_id (ScintillaObject *sci, uptr_t id); sptr_t scintilla_send_message (ScintillaObject *sci,unsigned int iMessage, uptr_t wParam, sptr_t lParam); void scintilla_release_resources(void); #define SCINTILLA_NOTIFY "sci-notify" #ifdef __cplusplus } #endif #endif #endif
1,418
C++
.h
38
35.736842
106
0.771763
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,296
SciNamespace.h
Studio3T_robomongo/src/third-party/qscintilla-2.8.4/sources/Qt4Qt5/SciNamespace.h
// Support for building the Scintilla code in the Scintilla namespace using the // -DSCI_NAMESPACE compiler flag. // // Copyright (c) 2014 Riverbank Computing Limited <info@riverbankcomputing.com> // // This file is part of QScintilla. // // This file may be used under the terms of the GNU General Public // License versions 2.0 or 3.0 as published by the Free Software // Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3 // included in the packaging of this file. Alternatively you may (at // your option) use any later version of the GNU General Public // License if such license has been publicly approved by Riverbank // Computing Limited (or its successors, if any) and the KDE Free Qt // Foundation. In addition, as a special exception, Riverbank gives you // certain additional rights. These rights are described in the Riverbank // GPL Exception version 1.1, which can be found in the file // GPL_EXCEPTION.txt in this package. // // If you are unsure which license is appropriate for your use, please // contact the sales department at sales@riverbankcomputing.com. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #ifndef _SCINAMESPACE_H #define _SCINAMESPACE_H #ifdef SCI_NAMESPACE #define QSCI_SCI_NAMESPACE(name) Scintilla::name #define QSCI_BEGIN_SCI_NAMESPACE namespace Scintilla { #define QSCI_END_SCI_NAMESPACE }; #else #define QSCI_SCI_NAMESPACE(name) name #define QSCI_BEGIN_SCI_NAMESPACE #define QSCI_END_SCI_NAMESPACE #endif #endif
1,602
C++
.h
36
43.277778
79
0.78105
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,316
qsciglobal.h
Studio3T_robomongo/src/third-party/qscintilla-2.8.4/sources/Qt4Qt5/Qsci/qsciglobal.h
// This module defines various things common to all of the Scintilla Qt port. // // Copyright (c) 2014 Riverbank Computing Limited <info@riverbankcomputing.com> // // This file is part of QScintilla. // // This file may be used under the terms of the GNU General Public // License versions 2.0 or 3.0 as published by the Free Software // Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3 // included in the packaging of this file. Alternatively you may (at // your option) use any later version of the GNU General Public // License if such license has been publicly approved by Riverbank // Computing Limited (or its successors, if any) and the KDE Free Qt // Foundation. In addition, as a special exception, Riverbank gives you // certain additional rights. These rights are described in the Riverbank // GPL Exception version 1.1, which can be found in the file // GPL_EXCEPTION.txt in this package. // // If you are unsure which license is appropriate for your use, please // contact the sales department at sales@riverbankcomputing.com. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #ifndef QSCIGLOBAL_H #define QSCIGLOBAL_H #ifdef __APPLE__ extern "C++" { #endif #include <qglobal.h> #define QSCINTILLA_VERSION 0x020804 #define QSCINTILLA_VERSION_STR "2.8.4" // Under Windows, define QSCINTILLA_MAKE_DLL to create a Scintilla DLL, or // define QSCINTILLA_DLL to link against a Scintilla DLL, or define neither // to either build or link against a static Scintilla library. #if defined(Q_OS_WIN) #if defined(QSCINTILLA_DLL) #define QSCINTILLA_EXPORT __declspec(dllimport) #elif defined(QSCINTILLA_MAKE_DLL) #define QSCINTILLA_EXPORT __declspec(dllexport) #endif #endif #if !defined(QSCINTILLA_EXPORT) #define QSCINTILLA_EXPORT #endif #if !defined(QT_BEGIN_NAMESPACE) #define QT_BEGIN_NAMESPACE #define QT_END_NAMESPACE #endif #ifdef __APPLE__ } #endif #endif
2,028
C++
.h
52
37.634615
79
0.778174
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,442
gtest-port-arch.h
Studio3T_robomongo/src/third-party/googletest-1.8.1/googletest/include/gtest/internal/gtest-port-arch.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines the GTEST_OS_* macro. // It is separate from gtest-port.h so that custom/gtest-port.h can include it. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ // Determines the platform on which Google Test is compiled. #ifdef __CYGWIN__ # define GTEST_OS_CYGWIN 1 #elif defined __SYMBIAN32__ # define GTEST_OS_SYMBIAN 1 #elif defined _WIN32 # define GTEST_OS_WINDOWS 1 # ifdef _WIN32_WCE # define GTEST_OS_WINDOWS_MOBILE 1 # elif defined(__MINGW__) || defined(__MINGW32__) # define GTEST_OS_WINDOWS_MINGW 1 # elif defined(WINAPI_FAMILY) # include <winapifamily.h> # if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) # define GTEST_OS_WINDOWS_DESKTOP 1 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) # define GTEST_OS_WINDOWS_PHONE 1 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) # define GTEST_OS_WINDOWS_RT 1 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE) # define GTEST_OS_WINDOWS_PHONE 1 # define GTEST_OS_WINDOWS_TV_TITLE 1 # else // WINAPI_FAMILY defined but no known partition matched. // Default to desktop. # define GTEST_OS_WINDOWS_DESKTOP 1 # endif # else # define GTEST_OS_WINDOWS_DESKTOP 1 # endif // _WIN32_WCE #elif defined __APPLE__ # define GTEST_OS_MAC 1 # if TARGET_OS_IPHONE # define GTEST_OS_IOS 1 # endif #elif defined __FreeBSD__ # define GTEST_OS_FREEBSD 1 #elif defined __Fuchsia__ # define GTEST_OS_FUCHSIA 1 #elif defined __linux__ # define GTEST_OS_LINUX 1 # if defined __ANDROID__ # define GTEST_OS_LINUX_ANDROID 1 # endif #elif defined __MVS__ # define GTEST_OS_ZOS 1 #elif defined(__sun) && defined(__SVR4) # define GTEST_OS_SOLARIS 1 #elif defined(_AIX) # define GTEST_OS_AIX 1 #elif defined(__hpux) # define GTEST_OS_HPUX 1 #elif defined __native_client__ # define GTEST_OS_NACL 1 #elif defined __NetBSD__ # define GTEST_OS_NETBSD 1 #elif defined __OpenBSD__ # define GTEST_OS_OPENBSD 1 #elif defined __QNX__ # define GTEST_OS_QNX 1 #endif // __CYGWIN__ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
3,723
C++
.h
97
37.268041
79
0.760696
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,452
gtest.h
Studio3T_robomongo/src/third-party/googletest-1.8.1/googletest/include/gtest/internal/custom/gtest.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** #ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
1,843
C++
.h
35
51.6
73
0.782946
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,453
gtest-printers.h
Studio3T_robomongo/src/third-party/googletest-1.8.1/googletest/include/gtest/internal/custom/gtest-printers.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // This file provides an injection point for custom printers in a local // installation of gTest. // It will be included from gtest-printers.h and the overrides in this file // will be visible to everyone. // // Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** #ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
2,079
C++
.h
40
50.925
75
0.783505
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,454
gtest-port.h
Studio3T_robomongo/src/third-party/googletest-1.8.1/googletest/include/gtest/internal/custom/gtest-port.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** #ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
1,858
C++
.h
35
52.028571
73
0.783086
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,460
sample1.h
Studio3T_robomongo/src/third-party/googletest-1.8.1/googletest/samples/sample1.h
// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. #ifndef GTEST_SAMPLES_SAMPLE1_H_ #define GTEST_SAMPLES_SAMPLE1_H_ // Returns n! (the factorial of n). For negative n, n! is defined to be 1. int Factorial(int n); // Returns true iff n is a prime number. bool IsPrime(int n); #endif // GTEST_SAMPLES_SAMPLE1_H_
1,893
C++
.h
36
51.444444
75
0.776458
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,477
gmock-matchers.h
Studio3T_robomongo/src/third-party/googletest-1.8.1/googlemock/include/gmock/internal/custom/gmock-matchers.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Injection point for custom user configurations. See README for details // // GOOGLETEST_CM0002 DO NOT DELETE #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
1,861
C++
.h
35
52.142857
73
0.786301
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,478
gmock-generated-actions.h
Studio3T_robomongo/src/third-party/googletest-1.8.1/googlemock/include/gmock/internal/custom/gmock-generated-actions.h
// This file was GENERATED by command: // pump.py gmock-generated-actions.h.pump // DO NOT EDIT BY HAND!!! // GOOGLETEST_CM0002 DO NOT DELETE #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
365
C++
.h
7
50.714286
73
0.785915
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,479
gmock-port.h
Studio3T_robomongo/src/third-party/googletest-1.8.1/googlemock/include/gmock/internal/custom/gmock-port.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** // GOOGLETEST_CM0002 DO NOT DELETE #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
1,894
C++
.h
36
51.527778
73
0.783288
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
15,480
person.h
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/tests/qobjecthelper/person.h
/* This file is part of qjson * * Copyright (C) 2009 Till Adam <adam@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef PERSON_H #define PERSON_H #include <QtCore/QDate> #include <QtCore/QtGlobal> #include <QtCore/QObject> #include <QtCore/QVariant> class Person : public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(int phoneNumber READ phoneNumber WRITE setPhoneNumber) Q_PROPERTY(Gender gender READ gender WRITE setGender) Q_PROPERTY(QDate dob READ dob WRITE setDob) Q_PROPERTY(QVariant customField READ customField WRITE setCustomField) Q_PROPERTY(quint16 luckyNumber READ luckyNumber WRITE setLuckyNumber) Q_ENUMS(Gender) public: Person(QObject* parent = 0); ~Person(); QString name() const; void setName(const QString& name); int phoneNumber() const; void setPhoneNumber(const int phoneNumber); enum Gender {Male, Female}; void setGender(Gender gender); Gender gender() const; QDate dob() const; void setDob(const QDate& dob); QVariant customField() const; void setCustomField(const QVariant& customField); const quint16 luckyNumber() const; void setLuckyNumber(const quint16 luckyNumber); private: QString m_name; int m_phoneNumber; Gender m_gender; QDate m_dob; QVariant m_customField; quint16 m_luckyNumber; }; #endif
2,082
C++
.h
60
31.15
76
0.747138
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
15,481
cmdlineparser.h
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/tests/cmdline_tester/cmdlineparser.h
/* This file is part of qjson * * Copyright (C) 2010 Flavio Castelli <flavio@castelli.name> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef CMDLINEPARSER_H #define CMDLINEPARSER_H #include <QtCore/QCoreApplication> #include <QtCore/QStringList> #include <QJson/Serializer> namespace QJson { class CmdLineParser { public: enum Result {Ok, Help, Error}; CmdLineParser(const QStringList &arguments); Result parse(); void setIndentationMode(const IndentMode &mode); IndentMode indentationMode() const; QString helpFile() const; QString file() const; bool serialize(); bool quiet(); void showMessage(const QString &msg, bool error); private: bool hasMoreArgs() const; const QString &nextArg(); void handleSetIndentationMode(); QStringList m_arguments; int m_pos; IndentMode m_indentationMode; QString m_file; bool m_serialize; bool m_quiet; static const QString m_helpMessage; QString m_error; }; } #endif
1,750
C++
.h
53
28.471698
76
0.714709
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,484
qjson_debug.h
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/src/qjson_debug.h
/* This file is part of qjson * * Copyright (C) 2009 Michael Leupold <lemma@confuego.org> * Copyright (C) 2013 Silvio Moioli <silvio@moioli.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef QJSON_DEBUG_H #define QJSON_DEBUG_H #include <QtCore/QDebug> // define qjsonDebug() #ifdef QJSON_VERBOSE_DEBUG_OUTPUT inline QDebug qjsonDebug() { return QDebug(QtDebugMsg); } #else #define qjsonDebug() if(false) QDebug(QtDebugMsg) #endif #endif
1,147
C++
.h
30
35.666667
76
0.750225
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,485
qjson_export.h
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/src/qjson_export.h
/* This file is part of the KDE project Copyright (C) 2009 Pino Toscano <pino@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef QJSON_EXPORT_H #define QJSON_EXPORT_H #include <QtCore/qglobal.h> #ifndef QJSON_STATIC # ifndef QJSON_EXPORT # if defined(QJSON_MAKEDLL) /* We are building this library */ # define QJSON_EXPORT Q_DECL_EXPORT # else /* We are using this library */ # define QJSON_EXPORT Q_DECL_IMPORT # endif # endif #endif #ifndef QJSON_EXPORT # define QJSON_EXPORT #endif #endif
1,205
C++
.h
32
34.53125
76
0.753661
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,496
Makefile.inc
Studio3T_robomongo/src/third-party/libssh2-1.9.0/sources/Makefile.inc
CSOURCES = channel.c comp.c crypt.c hostkey.c kex.c mac.c misc.c \ packet.c publickey.c scp.c session.c sftp.c userauth.c transport.c \ version.c knownhost.c agent.c $(CRYPTO_CSOURCES) pem.c keepalive.c global.c \ blowfish.c bcrypt_pbkdf.c HHEADERS = libssh2_priv.h $(CRYPTO_HHEADERS) transport.h channel.h comp.h \ mac.h misc.h packet.h userauth.h session.h sftp.h crypto.h blf.h
386
C++
.inc
6
62.5
78
0.757256
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,497
Makefile.WinCNG.inc
Studio3T_robomongo/src/third-party/libssh2-1.9.0/sources/Makefile.WinCNG.inc
CRYPTO_CSOURCES = wincng.c CRYPTO_HHEADERS = wincng.h CRYPTO_LTLIBS = $(LTLIBBCRYPT) $(LTLIBCRYPT32)
101
C++
.inc
3
32.666667
46
0.785714
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,498
Makefile.inc
Studio3T_robomongo/src/third-party/libssh2-1.7.0/sources/Makefile.inc
CSOURCES = channel.c comp.c crypt.c hostkey.c kex.c mac.c misc.c \ packet.c publickey.c scp.c session.c sftp.c userauth.c transport.c \ version.c knownhost.c agent.c $(CRYPTO_CSOURCES) pem.c keepalive.c global.c HHEADERS = libssh2_priv.h $(CRYPTO_HHEADERS) transport.h channel.h comp.h \ mac.h misc.h packet.h userauth.h session.h sftp.h crypto.h
351
C++
.inc
5
68.4
76
0.75942
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,499
main.cpp
yangyangwithgnu_hardseed/src/main.cpp
#include <iostream> #include <string> #include <algorithm> #include <iterator> #include <sstream> #include <cstring> #include <cstdlib> #include <cerrno> #include <unistd.h> #include <limits.h> #include <sys/stat.h> #include <sys/types.h> #include "lib/helper/Webpage.h" #include "lib/self/Aicheng.h" #include "lib/self/Caoliu.h" #include "lib/helper/Time.h" #include "lib/helper/CmdlineOption.h" #include "lib/helper/RichTxt.h" #include "lib/helper/Misc.h" #include "lib/3rd/json11/json11.hpp" using namespace std; using namespace json11; static const string g_softname(RichTxt::bold_on + "hardseed" + RichTxt::bold_off); static const string g_version("0.2.14"); static const string g_myemail("yangyangwithgnu@yeah.net"); static const string g_myemail_color(RichTxt::bold_on + RichTxt::foreground_green + g_myemail + RichTxt::reset_all); static const string g_mywebspace("http://yangyangwithgnu.github.io/"); static const string g_mywebspace_color(RichTxt::bold_on + RichTxt::foreground_green + g_mywebspace + RichTxt::reset_all); static void showSexyGirl (void) { cout << endl << ".================================================================." << endl << //"|| *hardseed* vx.y.z ||" << endl << "|| " << g_softname << " v" << g_version << " ||" << endl << "|'--------------------------------------------------------------'|" << endl << "|| -- SEX IS ZERO (0), so, who wanna be the ONE (1), aha? ||" << endl << "|'=============================================================='|" << endl << "|| .::::. ||" << endl << "|| .::::::::. ||" << endl << "|| ::::::::::: ||" << endl << "|| ':::::::::::.. ||" << endl << "|| .:::::::::::::::' ||" << endl << "|| '::::::::::::::.` ||" << endl << "|| .::::::::::::::::.' ||" << endl << "|| .::::::::::::.. ||" << endl << "|| .::::::::::::::'' ||" << endl << "|| .:::. '::::::::'':::: ||" << endl << "|| .::::::::. ':::::' ':::: ||" << endl << "|| .::::':::::::. ::::: '::::. ||" << endl << "|| .:::::' ':::::::::. :::::. ':::. ||" << endl << "|| .:::::' ':::::::::.::::::. '::. ||" << endl << "|| .::::'' ':::::::::::::::' '::. ||" << endl << "|| .::'' '::::::::::::::' ::.. ||" << endl << "|| ..:::: ':::::::::::' :'''` ||" << endl << "|| ..''''':' '::::::.' ||" << endl << "|'=============================================================='|" << endl << //"|| yangyangwithgnu@yeah.net ||" << endl << "|| " << g_myemail_color << " ||" << endl << //"|| http://yangyangwithgnu.github.io/ ||" << endl << "|| " << g_mywebspace_color << " ||" << endl << "'================================================================'" << endl; } static void showHelpInfo (void) { cout << endl; cout << g_softname << " is a batch seeds and pictures download utiltiy from CaoLiu and AiCheng forum. " << "It's easy and simple to use. Usually, you could issue it as follow: " << endl << " $ hardseed" << endl << "or" << endl << " $ hardseed --saveas-path ~/downloads --concurrent-tasks 4 --topics-range 8 64" << " --av-class aicheng_west --timeout-download-picture 32 --hate X-Art --proxy http://127.0.0.1:8087" << endl; cout << endl; cout << " --help" << endl << " Show this help infomation what you are seeing. " << endl; cout << endl; cout << " --version" << endl << " Show current version. " << endl; cout << endl; cout << " --av-class" << endl << " There are 13 av classes: caoliu_west_reposted, caoliu_cartoon_reposted, " << "caoliu_asia_mosaicked_reposted, caoliu_asia_non_mosaicked_reposted, caoliu_west_original, " << "caoliu_cartoon_original, caoliu_asia_mosaicked_original, caoliu_asia_non_mosaicked_original, " << "caoliu_selfie, aicheng_west, aicheng_cartoon, aicheng_asia_mosaicked and aicheng_asia_non_mosaicked. " << endl << " As the name implies, \"caoliu\" stands for CaoLiu forum, \"aicheng\" for AiCheng forum, " << "\"reposted\" and \"original\" are clearity, and the \"selfie\" is photos by oneself, you konw " << "which one is your best lover (yes, only one). " << endl << " The default is aicheng_asia_mosaicked. " << endl; cout << endl; cout << " --concurrent-tasks" << endl << " You can set more than one proxy, each proxy could more than one concurrent tasks. This option " << "set the number of concurrent tasks of each prox. " << endl << " The default number is 8. " << endl; cout << endl; cout << " --timeout-download-picture" << endl << " Some pictures too big to download in few seconds. So, you should set the download picture " << "timeout seconds. " << endl << " The default timeout is 16 seconds." << endl; cout << endl; cout << " --topics-range" << endl << " Set the range of to download topics. E.G.: " << endl << " --topics-range 2 16" << endl << " --topics-range 8 (I.E., --topics-range 1 8)" << endl << " --topics-range -1 (I.E., all topics of this av class)" << endl << " The default topics range is 1 to 64. " << endl; cout << endl; cout << " --saveas-path" << endl << " Set the path to save seeds and pictures. The rule of dir: [avclass][range]@hhmmss. E.G., " << "[aicheng_west][2~32]@124908/. " << endl << " The default directory is home directory (or windows is C:\\). " << endl; cout << endl; cout << " --hate" << endl << " If you hate some subject topics, you can ignore them by setting this option with keywords " << "in topic title, split by space-char ' ', and case sensitive. E.G., --hate 孕妇 重口味. " << "When --hate keywords list conflict with --like, --hate first. " << endl; cout << endl; cout << " --like" << endl << " If you like some subject topics, you can grab them by setting this option with keywords " << "in topic title, split by space-char ' ', and case sensitive. E.G., --like 苍井空 小泽玛利亚. " << "When --like keywords list conflict with --hate, --hate first. " << endl; cout << endl; cout << " --proxy" << endl << " As you know, the government likes blocking adult websites, so, I do suggest you to set " << "--proxy option. Hardseed supports more proxys: " << endl << " a) GoAgent (STRONGLY recommended), --proxy http://127.0.0.1:8087" << endl << " b) shadowsocks, --proxy socks5://127.0.0.1:1080, or socks5h://127.0.0.1:1080" << endl << " c) SSH, --proxy socks4://127.0.0.1:7070" << endl << " d) VPN (PPTP and openVPN), --proxy \"\"" << endl << " It is important that you should know, you can set more proxys at the same time, split by " << "space-char ' '. As the --concurrent-tasks option says, each proxy could more than one concurrent " << "tasks, now, what about more proxys? Yes, yes, the speed of downloading seed and pictures is " << "very very fast. E.G., --concurrent-tasks 8 --proxy http://127.0.0.1:8087 socks5://127.0.0.1:1080 " << "socks4://127.0.0.1:7070, the number of concurrent tasks is 8*3. " << endl << " If you wanna how to install and configure various kinds of proxy, please access my homepage " << "\"3.2 搭梯翻墙\" https://github.com/yangyangwithgnu/the_new_world_linux#3.2 " << endl << " If you are not good at computer, there is a newest goagent for floks who are not good at computer " << "by me, yes, out of box. see https://github.com/yangyangwithgnu/goagent_out_of_box_yang " << " The default http://127.0.0.1:8087. " << endl; cout << endl; cout << " That's all. Any suggestions let me know by " << g_myemail_color << " or " << g_mywebspace_color << ", big thanks to you. Kiddo, take care of your body. :-)" << endl << endl; } static void showVersionInfo (void) { cout << "hardseed version " << g_version << endl << "email " << g_myemail << endl << "webspace " << g_mywebspace << endl << endl; } static bool parseTopicsRangeArgument ( const vector<string>& topicsrange_arguments_list, unsigned& topics_range_begin, unsigned& topics_range_end ) { if (topicsrange_arguments_list.empty()) { return(false); } string begin_str = topicsrange_arguments_list[0]; string end_str; if (topicsrange_arguments_list.size() < 2) { end_str = begin_str; begin_str = "1"; } else { end_str = topicsrange_arguments_list[1]; } unsigned begin_tmp; if ( 0 == (begin_tmp = strtoul(begin_str.c_str(), nullptr, 0)) && '0' != begin_str[0] ) { return(false); } unsigned end_tmp; if ( 0 == (end_tmp = strtoul(end_str.c_str(), nullptr, 0)) && '0' != end_str[0] ) { return(false); } if (begin_tmp > end_tmp) { return(false); } topics_range_begin = begin_tmp; topics_range_end = end_tmp; return(true); } static void getPortalUrls (string& caoliu_portal_url, string& aicheng_portal_url) { //#ifdef CYGWIN caoliu_portal_url = "http://t66y.com/"; aicheng_portal_url = "http://www.ac168.info/bt/"; //#else //static const string portals_file_url("https://raw.githubusercontent.com/yangyangwithgnu/hardseed/master/config/portals_list.json"); //Webpage portals_list_webpage(portals_file_url); //if (!portals_list_webpage.isLoaded()) { //cerr << "ERROR! fail to load " << portals_file_url << endl; //exit(EXIT_FAILURE); //} //const string& portals_file_txt = portals_list_webpage.getTxt(); //string json_err_msg; //const auto json_portal_urls_list = Json::parse(portals_file_txt, json_err_msg); //if (!json_err_msg.empty()) { //cerr << "ERROR! fail to parse the portal URLs list JSON. because " //<< json_err_msg //<< endl; //exit(EXIT_FAILURE); //} //// caoliu 和 aicheng 论坛入口 URL 以 json 格式存放在本项目托管空间中,格式如下: /* * { * "caoliu": "http://cl.clme.me/", * "aicheng": "http://www.ac168.info/", * } */ //caoliu_portal_url = json_portal_urls_list["caoliu"].string_value(); //aicheng_portal_url = json_portal_urls_list["aicheng"].string_value(); //if (caoliu_portal_url.empty() || aicheng_portal_url.empty()) { //cerr << "ERROR! fail to parse caoliu and aicheng portal URL. " << endl; //exit(EXIT_FAILURE); //} //#endif } int main (int argc, char* argv[]) { // parse command line options // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> CmdlineOption cmdline_options((unsigned)argc, argv); vector<string> cmdline_arguments_list; // --help, first high priority, ignore other options if (cmdline_options.hasOption("--help")) { showHelpInfo(); return(EXIT_SUCCESS); } // --version, second high priority, ignore other options if (cmdline_options.hasOption("--version")) { showVersionInfo(); return(EXIT_SUCCESS); } // show the sexy girl ASCII art showSexyGirl(); cout << endl; sleep(2); // prompt turn on the goagent cout << RichTxt::bold_on << "************************ !! IMPORTANCE !! ************************" << endl << "******** please make sure the proxy program is running *********" << endl << "************************ !! IMPORTANCE !! ************************" << endl << RichTxt::bold_off << endl; // --av-class // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> cout << "Your command arguments: " << endl; string av_class_name("aicheng_asia_mosaicked"); cmdline_arguments_list = cmdline_options.getArgumentsList("--av-class"); if (!cmdline_arguments_list.empty()) { av_class_name = cmdline_arguments_list[0]; } bool b_aicheng = true; Caoliu::AvClass caoliu_av_class = Caoliu::asia_mosaicked_original; Aicheng::AvClass aicheng_av_class = Aicheng::asia_mosaicked; if ("caoliu_west_original" == av_class_name) { caoliu_av_class = Caoliu::west_original; b_aicheng = false; } else if ("caoliu_cartoon_original" == av_class_name) { caoliu_av_class = Caoliu::cartoon_original; b_aicheng = false; } else if ("caoliu_asia_mosaicked_original" == av_class_name) { caoliu_av_class = Caoliu::asia_mosaicked_original; b_aicheng = false; } else if ("caoliu_asia_non_mosaicked_original" == av_class_name) { caoliu_av_class = Caoliu::asia_non_mosaicked_original; b_aicheng = false; } else if ("caoliu_west_reposted" == av_class_name) { caoliu_av_class = Caoliu::west_reposted; b_aicheng = false; } else if ("caoliu_cartoon_reposted" == av_class_name) { caoliu_av_class = Caoliu::cartoon_reposted; b_aicheng = false; } else if ("caoliu_asia_mosaicked_reposted" == av_class_name) { caoliu_av_class = Caoliu::asia_mosaicked_reposted; b_aicheng = false; } else if ("caoliu_asia_non_mosaicked_reposted" == av_class_name) { caoliu_av_class = Caoliu::asia_non_mosaicked_reposted; b_aicheng = false; } else if ("caoliu_selfie" == av_class_name) { caoliu_av_class = Caoliu::selfie; b_aicheng = false; } else if ("aicheng_west" == av_class_name) { aicheng_av_class = Aicheng::west; } else if ("aicheng_asia_mosaicked" == av_class_name) { aicheng_av_class = Aicheng::asia_mosaicked; } else if ("aicheng_cartoon" == av_class_name) { aicheng_av_class = Aicheng::cartoon; } else if ("aicheng_asia_non_mosaicked" == av_class_name) { aicheng_av_class = Aicheng::asia_non_mosaicked; } else { cerr << "ERROR! the --av-class argument invalid. More info please see --help. " << endl; return(EXIT_FAILURE); } cout << " the av class \"" << RichTxt::bold_on << av_class_name << RichTxt::bold_off << "\"; " << endl; // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // --timeout-download-picture unsigned timeout_download_pic = 16; // default timeout seconds cmdline_arguments_list = cmdline_options.getArgumentsList("--timeout-download-picture"); if (!cmdline_arguments_list.empty()) { unsigned tmp = strtoul(cmdline_arguments_list[0].c_str(), nullptr, 0); if (tmp > 0) { timeout_download_pic = tmp; } } cout << " the download picture timeout seconds " << "\"" << RichTxt::bold_on << timeout_download_pic << RichTxt::bold_off << "\"; " << endl; // --topics-range, E.G.: // --topics-range 2 16, // --topics-range 8 (I.E., --topics-range 1 8), // --topics-range 4 -1 (I.E., all topics of this class av) unsigned topics_range_begin = 1, topics_range_end = 64; // default range cmdline_arguments_list = cmdline_options.getArgumentsList("--topics-range"); if (!cmdline_arguments_list.empty()) { if (!parseTopicsRangeArgument(cmdline_arguments_list, topics_range_begin, topics_range_end)) { cerr << "ERROR! --topics-range argument setting wrong! " << endl; return(EXIT_FAILURE); } } cout << " the range of parsing topics " << RichTxt::bold_on << "[" << topics_range_begin << "~" << topics_range_end << "]" << RichTxt::bold_off << "; " << endl; // --saveas-path. // create dir to save seeds and pictures. the rule of dir: [avclass][range]@hhmmss. // E.G., [aicheng_west][8~16]@211159. default home directory. // >>>>>>>>>>>>>>>>>> string path; cmdline_arguments_list = cmdline_options.getArgumentsList("--saveas-path"); if (cmdline_arguments_list.empty()) { #ifdef CYGWIN const char* p_home = "C:\\"; #else const char* p_home = getenv("HOME"); #endif if (nullptr == p_home) { cerr << "ERROR! --saveas-path argument setting wrong! " << endl; return(EXIT_FAILURE); } path = p_home; } else { path = cmdline_arguments_list[0]; } path += "/["; // 1st, av class path += av_class_name; path += "]"; // 2nd, range path += "[" + convNumToStr(topics_range_begin) + "~" + convNumToStr(topics_range_end) + "]@"; // 3rd, time Time current_time; path += current_time.getHour(2) + current_time.getMinute(2) + current_time.getSecond(2); path += "/"; #ifdef CYGWIN // windows path style replace(path.begin(), path.end(), '/', '\\'); #endif // create dir if (-1 == mkdir(path.c_str(), 0755)) { cerr << "ERROR! cannot create " << path << ", " << strerror(errno) << endl; return(EXIT_FAILURE); } #ifndef CYGWIN // convert raw path to standard absolute path. To call realpath() success, // path must have created. char buffer[PATH_MAX]; realpath(path.c_str(), buffer); path = buffer; #endif cout << " the path to save seeds and pictures \"" << RichTxt::bold_on << path << RichTxt::bold_off << "\"; " << endl; // <<<<<<<<<<<<<<<<<< // --concurrent-tasks unsigned threads_total = 8; // the default number of threads cmdline_arguments_list = cmdline_options.getArgumentsList("--concurrent-tasks"); if (!cmdline_arguments_list.empty()) { unsigned tmp = strtoul(cmdline_arguments_list[0].c_str(), nullptr, 0); if (tmp <= 0) { cerr << "ERROR! --concurrent-tasks argument setting wrong. " << endl; return(EXIT_FAILURE); } threads_total = tmp; } cout << " the number of concurrent tasks \"" << RichTxt::bold_on << threads_total << RichTxt::bold_off << "\"; " << endl; // --hate. ignore the topics by user setting keywords in topic title, split by space-char ' '. // for example: --hate aa bb cc "d d". vector<string> hate_keywords_list = { "连发", "連发", "连發", "連發", "连弹", "★㊣", "合辑", "合集", "合輯", "nike", "最新の美女骑兵㊣", "精選", "精选" }; // force to ignore the all-in-one topics cmdline_arguments_list = cmdline_options.getArgumentsList("--hate"); if (!cmdline_arguments_list.empty()) { hate_keywords_list.insert(hate_keywords_list.end(), cmdline_arguments_list.begin(), cmdline_arguments_list.end()); } cout << " ignore some topics which include the keywords as follow \"" << RichTxt::bold_on; if (hate_keywords_list.empty()) { cout << " "; } else { copy(hate_keywords_list.cbegin(), hate_keywords_list.cend(), ostream_iterator<const string&>(cout, ", ")); } cout << RichTxt::bold_off << "\b\b\"; " << endl; // --like. vector<string> like_keywords_list; cmdline_arguments_list = cmdline_options.getArgumentsList("--like"); if (!cmdline_arguments_list.empty()) { like_keywords_list.assign(cmdline_arguments_list.begin(), cmdline_arguments_list.end()); } cout << " just parse topics which include the kewords as follow \"" << RichTxt::bold_on; if (like_keywords_list.empty()) { cout << " "; } else { copy(like_keywords_list.cbegin(), like_keywords_list.cend(), ostream_iterator<const string&>(cout, ", ")); } cout << RichTxt::bold_off << "\b\b\"; " << endl; // --proxy. prompt user to use proxy, because the caoliu bbs maybe block IP vector<string> proxy_addrs_list = {"http://127.0.0.1:8087"}; // the default proxy is GoAgent cmdline_arguments_list = cmdline_options.getArgumentsList("--proxy"); if (!cmdline_arguments_list.empty()) { proxy_addrs_list = cmdline_arguments_list; } cout << " the proxy \"" << RichTxt::bold_on; copy(proxy_addrs_list.cbegin(), proxy_addrs_list.cend(), ostream_iterator<string>(cout, ", ")); cout << "\b\b" << RichTxt::bold_off << "\". " << endl << endl; // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // 获取 caoliu 和 aicheng 两个论坛的入口 URL string caoliu_portal_url, aicheng_portal_url; getPortalUrls(caoliu_portal_url, aicheng_portal_url); // download pictures and seed if (b_aicheng) { Aicheng aicheng( aicheng_portal_url, aicheng_av_class, proxy_addrs_list, topics_range_begin, topics_range_end, hate_keywords_list, like_keywords_list, threads_total * proxy_addrs_list.size(), timeout_download_pic, path ); } else { Caoliu caoliu ( caoliu_portal_url, caoliu_av_class, proxy_addrs_list, topics_range_begin, topics_range_end, hate_keywords_list, like_keywords_list, threads_total * proxy_addrs_list.size(), timeout_download_pic, path ); } cout << endl; return(EXIT_SUCCESS); }
22,691
C++
.cpp
459
41.346405
137
0.522721
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,503
Misc.cpp
yangyangwithgnu_hardseed/src/lib/helper/Misc.cpp
// last modified #include "Misc.h" #include <algorithm> #include <iostream> #include <iterator> #include <cstdlib> #include <cstdio> #include <bitset> #include <ctime> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> using std::bitset; using std::cout; using std::cerr; using std::endl; using std::make_pair; using std::ostream_iterator; // split raw string to more sub-str by token-chars. // note: // 0) case sensitive; // 1) if there are consecutive two token-chars in raw string, splitStr() // will make a empty sub-str into splited_substr_list. void splitStr ( const string& str, const string& tokens_list, vector<string>& splited_substr_list, vector<char>& appeared_tokens_list ) { size_t begin_pos = 0, end_pos; while (begin_pos < str.size()) { const auto iter_token = find_first_of( str.cbegin() + (int)begin_pos, str.cend(), tokens_list.cbegin(), tokens_list.cend() ); if (str.cend() == iter_token) { splited_substr_list.push_back(str.substr(begin_pos)); break; } appeared_tokens_list.push_back(*iter_token); end_pos = (unsigned)(iter_token - str.cbegin()); splited_substr_list.push_back(str.substr(begin_pos, end_pos - begin_pos)); begin_pos = end_pos + 1; } if (splited_substr_list[0].empty()) { splited_substr_list.erase(splited_substr_list.begin()); } } // first return is the string between keyword_begin and keyword_end; // second return is end_pos + keyword_end.size(). pair<string, size_t> fetchStringBetweenKeywords ( const string& txt, const string& keyword_begin, const string& keyword_end, size_t from_pos ) { const auto begin_pos = txt.find(keyword_begin, from_pos); if (string::npos == begin_pos) { //cerr << "WARNING! fetchStringBetweenKeywords() CANNOT find the keyword \"" << kyeword_begin << "\"" << endl; return(make_pair("", 0)); } const auto end_pos = txt.find(keyword_end, begin_pos + keyword_begin.size()); if (string::npos == end_pos) { //cerr << "WARNING! fetchStringBetweenKeywords() CANNOT find the keyword \"" << kyeword_end << "\"" << endl; return(make_pair("", 0)); } return(make_pair( txt.substr(begin_pos + keyword_begin.size(), end_pos - begin_pos - keyword_begin.size()), end_pos + keyword_end.size() )); } // get file size by FILE*. // return -1 if failure long getFileSize (FILE* fs) { // backup current offset long offset_bak = ftell(fs); // get the filesize fseek(fs, 0, SEEK_END); long file_size = ftell(fs); // restore last offset fseek(fs, offset_bak, SEEK_SET); return(file_size); } // process_name + process_id + thread_id + rand extern char *__progname; string makeRandomFilename (void) { static bool b_first = true; if (b_first) { srand((unsigned)time(NULL)); b_first = false; } const string& filename = string(__progname) + "_" + convNumToStr(getpid()) + "_" + convNumToStr(pthread_self()) + "_" + convNumToStr(rand()); #ifdef CYGWIN return("c:\\" + filename); #else return("/tmp/" + filename); #endif } // unicode 与 UTF8 间转换规则: // ================================================================================= // | unicode 符号范围 | UTF8编码方式 // n | (十六进制) | (二进制) // --+-----------------------+------------------------------------------------------ // 1 | 0000 0000 - 0000 007F | 0xxxxxxx // 2 | 0000 0080 - 0000 07FF | 110xxxxx 10xxxxxx // 3 | 0000 0800 - 0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx // 4 | 0001 0000 - 0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // 5 | 0020 0000 - 03FF FFFF | 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx // 6 | 0400 0000 - 7FFF FFFF | 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx // ================================================================================= // UTF8 中剩余的 x 用其 unicode 中各位从右向左填充,若还有多余的位则 0 填。如,"严" // 的 unicode 是 4E25(100111000100101),根据上表,可以发现 4E25 处在第三行的范围内 // (0000 0800-0000 FFFF),"严"的 UTF8 编码需要三个字节,即格式是 // "1110xxxx 10xxxxxx 10xxxxxx",然后,从"严"的最后一个二进制位开始,依次从后向前填 // 入格式中的 x,多出的位补 0。这样就得到了,"严"的 UTF8 编码是 // "11100100 10111000 10100101",转换成十六进制就是 E4B8A5。 // // 返回值:由于 UTF8 是变长编码格式,所以,需要返回转换后的 UTF8 编码有效字节数,以 // 具体值。 // // 注意: // 0)假定小尾存储; // 1)unicode 最多需要 4 个字节,UTF8 最多需要 6 个字节,所以,这就决定了型参类 // 型必须为 unsigned int,返回值类型为 unsigned long long; // // 更多细节参见:http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf-8.html pair<size_t, unsigned long long> convertUnicodeToUtf8 (unsigned int unicode) { if (unicode <= 0x0000007F) { return(make_pair(1, unicode)); } else if (0x00000080 <= unicode && unicode <= 0x000007FF) { bitset<16> unicode_bits(unicode); const string unicode_bits_str = unicode_bits.to_string<char, string::traits_type, string::allocator_type>(); string unicode_bits_str_reverse(unicode_bits_str.crbegin(), unicode_bits_str.crend()); unicode_bits_str_reverse.insert(6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 5, "000"); unicode_bits_str_reverse.resize(16); const bitset<16> masker(string(unicode_bits_str_reverse.crbegin(), unicode_bits_str_reverse.crend())); bitset<16> utf8_lower("1100000010000000"); bitset<16> utf8_bits = utf8_lower | masker; return(make_pair(2, utf8_bits.to_ullong())); } else if (0x00000800 <= unicode && unicode <= 0x0000FFFF) { bitset<16> unicode_bits(unicode); const string unicode_bits_str = unicode_bits.to_string<char, string::traits_type, string::allocator_type>(); string unicode_bits_str_reverse(unicode_bits_str.crbegin(), unicode_bits_str.crend()); unicode_bits_str_reverse.insert(6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6 + 2 + 4, "0000"); unicode_bits_str_reverse.resize(24); const bitset<24> masker(string(unicode_bits_str_reverse.crbegin(), unicode_bits_str_reverse.crend())); bitset<24> utf8_lower("111000001000000010000000"); bitset<24> utf8_bits = utf8_lower | masker; return(make_pair(3, utf8_bits.to_ullong())); } else if (0x00010000 <= unicode && unicode <= 0x0010FFFF) { bitset<32> unicode_bits(unicode); const string unicode_bits_str = unicode_bits.to_string<char, string::traits_type, string::allocator_type>(); string unicode_bits_str_reverse(unicode_bits_str.crbegin(), unicode_bits_str.crend()); unicode_bits_str_reverse.insert(6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6 + 2 + 6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6 + 2 + 6 + 2 + 3, "000"); unicode_bits_str_reverse.resize(32); const bitset<32> masker(string(unicode_bits_str_reverse.crbegin(), unicode_bits_str_reverse.crend())); bitset<32> utf8_lower("11110000100000001000000010000000"); bitset<32> utf8_bits = utf8_lower | masker; return(make_pair(4, utf8_bits.to_ullong())); } else if (0x00200000 <= unicode && unicode <= 0x03FFFFFF) { bitset<32> unicode_bits(unicode); const string unicode_bits_str = unicode_bits.to_string<char, string::traits_type, string::allocator_type>(); string unicode_bits_str_reverse(unicode_bits_str.crbegin(), unicode_bits_str.crend()); unicode_bits_str_reverse.insert(6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6 + 2 + 6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6 + 2 + 6 + 2 + 6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6 + 2 + 6 + 2 + 6 + 2 + 2, "00"); unicode_bits_str_reverse.resize(40); const bitset<40> masker(string(unicode_bits_str_reverse.crbegin(), unicode_bits_str_reverse.crend())); bitset<40> utf8_lower("1111100010000000100000001000000010000000"); bitset<40> utf8_bits = utf8_lower | masker; return(make_pair(5, utf8_bits.to_ullong())); } else if (0x04000000 <= unicode && unicode <= 0x7FFFFFFF) { bitset<64> unicode_bits(unicode); const string unicode_bits_str = unicode_bits.to_string<char, string::traits_type, string::allocator_type>(); string unicode_bits_str_reverse(unicode_bits_str.crbegin(), unicode_bits_str.crend()); unicode_bits_str_reverse.insert(6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6 + 2 + 6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6 + 2 + 6 + 2 + 6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6 + 2 + 6 + 2 + 6 + 2 + 6, "00"); unicode_bits_str_reverse.insert(6 + 2 + 6 + 2 + 6 + 2 + 6 + 2 + 6 + 2 + 1, "0"); unicode_bits_str_reverse.resize(48); const bitset<48> masker(string(unicode_bits_str_reverse.crbegin(), unicode_bits_str_reverse.crend())); bitset<48> utf8_lower("111111001000000010000000100000001000000010000000"); bitset<48> utf8_bits = utf8_lower | masker; return(make_pair(6, utf8_bits.to_ullong())); } else { cerr << "WARNING! " << unicode << "is not a vaild unicode. " << endl; return(make_pair(0, 0)); } } bool wait_cmd ( const string& cmd, const vector<string>& argv, int* p_exitCode, bool b_echo ) { bool b_executed_success = false; char** argv_tmp; // 回显命令行 if (b_echo) { copy(argv.cbegin(), argv.cend(), ostream_iterator<string>(cout, " ")); cout << endl; } // 将vector<string>中的命令行参数转换为char* [] argv_tmp = new char* [argv.size() + 1]; // !!!子进程中是否产生内存泄漏?? for (size_t i = 0; i != argv.size(); ++i) { argv_tmp[i] = const_cast<char*>(argv[i].c_str()); } argv_tmp[argv.size()] = NULL; // 运行并等待子进程 pid_t pid = fork(); if (0 == pid) { // 子进程 execvp(cmd.c_str(), argv_tmp); } else if (pid > 0) { // 父进程 int status; waitpid(pid, &status, 0); // 命令正常结束。即通过exit()正常退出,而非通过kill异常结束,与exit()的返回值无关 if (WIFEXITED(status)) { int exit_code = WEXITSTATUS(status); // 命令通过正常exit()结束时的返回值 if (EXIT_SUCCESS == exit_code) { b_executed_success = true; } if (NULL != p_exitCode) { *p_exitCode = exit_code; } } } delete [] argv_tmp; return (b_executed_success ); }
11,756
C++
.cpp
244
38.127049
118
0.595151
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,504
Caoliu.cpp
yangyangwithgnu_hardseed/src/lib/self/Caoliu.cpp
// last modified #include "Caoliu.h" #include <iostream> #include <iomanip> #include <algorithm> #include <iterator> #include <thread> #include <mutex> #include <cstdlib> #include <unistd.h> #include "CaoliuTopicsListWebpage.h" #include "CaoliuTopicWebpage.h" #include "RmdownSeedWebpage.h" #include "../helper/RichTxt.h" using namespace std; static mutex g_mtx; const string& Caoliu::getPortalWebpageUrl (void) const { return(portal_url_); } static const string& getTopicsListWebpagePartUrl (Caoliu::AvClass av_class) { // reposted static const string west_reposted_part_url("thread0806.php?fid=19"); static const string cartoon_reposted_part_url("thread0806.php?fid=24"); static const string asia_mosaicked_reposted_part_url("thread0806.php?fid=18"); static const string asia_non_mosaicked_reposted_part_url("thread0806.php?fid=17"); // original static const string west_original_part_url("thread0806.php?fid=4"); static const string cartoon_original_part_url("thread0806.php?fid=5"); static const string asia_mosaicked_original_part_url("thread0806.php?fid=15"); static const string asia_non_mosaicked_original_part_url("thread0806.php?fid=2"); // selfie static const string selfie_part_url("thread0806.php?fid=16"); switch (av_class) { case Caoliu::west_reposted: return(west_reposted_part_url); case Caoliu::cartoon_reposted: return(cartoon_reposted_part_url); case Caoliu::asia_mosaicked_reposted: return(asia_mosaicked_reposted_part_url); case Caoliu::asia_non_mosaicked_reposted: return(asia_non_mosaicked_reposted_part_url); case Caoliu::west_original: return(west_original_part_url); case Caoliu::cartoon_original: return(cartoon_original_part_url); case Caoliu::asia_mosaicked_original: return(asia_mosaicked_original_part_url); case Caoliu::asia_non_mosaicked_original: return(asia_non_mosaicked_original_part_url); case Caoliu::selfie: return(selfie_part_url); } } static const string getTopicsListWebpageUrl (const string& portal_url, Caoliu::AvClass av_class) { return(portal_url + getTopicsListWebpagePartUrl(av_class)); } static bool isThereInList ( const string& webpage_title, const vector<string>& ignore_keywords_list, string& which_keyword ) { for (const auto& e : ignore_keywords_list) { if (!e.empty() && string::npos != webpage_title.find(e)) { which_keyword = e; return(true); } } return(false); } static bool parseValidTopicsUrls ( Caoliu::AvClass av_class, const string& portal_url, const string& proxy_addr, unsigned range_begin, unsigned range_end, const vector<string>& hate_keywords_list, const vector<string>& like_keywords_list, vector<string>& valid_topics_urls_list, bool b_progress ) { valid_topics_urls_list.clear(); string current_url = getTopicsListWebpageUrl(portal_url, av_class); bool b_stop = false; unsigned topics_cnt = 0; while (!current_url.empty() && !b_stop) { CaoliuTopicsListWebpage caoliu_topicslist_webpage(portal_url, current_url, proxy_addr); if (!caoliu_topicslist_webpage.isLoaded()) { return(false); } const vector<pair<string, string>>& topics_title_and_url = caoliu_topicslist_webpage.getTitlesAndUrlsList(); for (const auto& e : topics_title_and_url) { if (++topics_cnt > range_end) { b_stop = true; break; } const string& topic_title = e.first; const string& topic_url = e.second; static const string o_flag(RichTxt::bold_on + "O" + RichTxt::bold_off); static const string x_flag("x"); // ignore the topics which do not in range if (topics_cnt < range_begin) { if (b_progress) { cout << x_flag << " " << flush; } continue; } // ignore the topics which contain hate keyword by user set string which_keyword; if (isThereInList(topic_title, hate_keywords_list, which_keyword)) { if (b_progress) { cout << x_flag << " " << flush; } continue; } // ignore the topics which do not contain like keyword by user set if ( !like_keywords_list.empty() && !isThereInList(topic_title, like_keywords_list, which_keyword) ) { if (b_progress) { cout << x_flag << " " << flush; } continue; } valid_topics_urls_list.push_back(topic_url); if (b_progress) { cout << o_flag << " " << flush; } } current_url = caoliu_topicslist_webpage.getNextpageUrl(); } return(true); } static void downloadTopicPicsAndSeed ( const string& topic_url, const string& proxy_addr, const string& path, unsigned timeout_download_pic, unsigned pictures_total, bool b_download_seed, bool b_show_info ) { CaoliuTopicWebpage caoliu_topics_webpage(topic_url, proxy_addr); // ready for the basename of pictures and seed. // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> string base_name; // from topic title // 0) delete the web logo info; // 1) clear the "/" in topictitle string, if the "/" present in filename, // linux will treat it as directory, again, clear the "\" for windows; static const vector<string> keyword_logos_list = {" 草榴社區 - powered by phpwind.net"}; const string& topic_webpage_title = caoliu_topics_webpage.getTitle(); auto keyword_logo_pos = string::npos; for (const auto& f : keyword_logos_list) { keyword_logo_pos = topic_webpage_title.find(f); if (string::npos != keyword_logo_pos) { break; } } remove_copy_if( topic_webpage_title.cbegin(), (string::npos == keyword_logo_pos) ? topic_webpage_title.cend() : topic_webpage_title.cbegin() + (int)keyword_logo_pos, back_inserter(base_name), [] (char ch) {return( '|' == ch || // invalid chars in windows-sytle filename '/' == ch || '<' == ch || '>' == ch || '?' == ch || '*' == ch || ':' == ch || '\\' == ch );} ); // 2) the path + filename max length must less than pathconf(, _PC_NAME_MAX) const unsigned filename_max_length_without_postfix = (unsigned)pathconf(path.c_str(), _PC_NAME_MAX) - string("99").size() // picture number - string(".torrent").size(); if (base_name.size() >= filename_max_length_without_postfix) { // the filename too long to create file. the way as following doesn't work, case filename encoding error: // base_name.resize(filename_max_length_without_postfix - 1), because this is string on char not wstring on wchar. // there is another stupid way, random name from 'a' to 'z' base_name.resize(16); generate( base_name.begin(), base_name.end(), [] () {return('a' + rand() % ('z' - 'a'));} ); base_name = "(rename)" + base_name; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // download all pictures //const vector<string>& urls = caoliu_topics_webpage.getPicturesUrlsList(); //for (const auto& e : urls) { ////cout << "------------" << endl; //cout << e << "\n\t"; //cout << caoliu_topics_webpage.getRemoteFiletype(e) << endl; ////cout << "------------" << endl; //} vector<string> fail_download_pics_urls_list; bool b_download_pics_success = caoliu_topics_webpage.downloadAllPictures( path, base_name, timeout_download_pic, fail_download_pics_urls_list, pictures_total ); // download seed bool b_downloaded_seed_success = true; if (b_download_seed) { b_downloaded_seed_success = false; if (!caoliu_topics_webpage.getSeedUrl().empty()) { RmdownSeedWebpage rm_seed_webpage(caoliu_topics_webpage.getSeedUrl(), proxy_addr); b_downloaded_seed_success = rm_seed_webpage.downloadSeed(path, base_name); } } // show result info if (!b_show_info) { return; } static const string success_info("success"); static const string fail_info = RichTxt::foreground_red + "failure" + RichTxt::reset_all; g_mtx.lock(); cout << " \"" << base_name << "\" - "; if (b_download_pics_success && b_downloaded_seed_success) { cout << success_info; } else { cout << fail_info << " (download error from " << topic_url << ". "; if (!b_download_pics_success) { cout << "pictures error: "; copy(fail_download_pics_urls_list.cbegin(), fail_download_pics_urls_list.cend(), ostream_iterator<const string&>(cout, ", ")); cout << "\b\b"; } if (b_download_seed && !b_downloaded_seed_success) { if (!b_download_pics_success) { cout << "; "; } cout << "seed error: " << caoliu_topics_webpage.getSeedUrl(); } cout << ")"; } cout << endl; g_mtx.unlock(); } static const string& getNextProxyAddr (const vector<string>& proxy_addrs_list) { if (proxy_addrs_list.empty()) { static const string empty_str(""); return(empty_str); } static unsigned current_pos; if (current_pos >= proxy_addrs_list.size()) { current_pos = 0; } return(proxy_addrs_list[current_pos++]); } Caoliu::Caoliu ( const string& portal_url, AvClass av_class, const vector<string>& proxy_addrs_list, unsigned range_begin, unsigned range_end, const vector<string>& hate_keywords_list, const vector<string>& like_keywords_list, unsigned threads_total, unsigned timeout_download_pic, const string& path ) : portal_url_(portal_url) { // parse the URLs of valid topics by: range, hate keywords, like keywords cout << "Parse the URLs of topics from " << range_begin << " to " << range_end << ": " << flush; vector<string> valid_topics_urls_list; parseValidTopicsUrls( av_class, portal_url, getNextProxyAddr(proxy_addrs_list), range_begin, range_end, hate_keywords_list, like_keywords_list, valid_topics_urls_list, true ); cout << endl; if (valid_topics_urls_list.empty()) { cout << "There is no topic which you like. " << endl; return; } cout << endl; // check just download picutures for dagaier? unsigned pictures_total = 2; bool b_download_seed = true; if (Caoliu::selfie == av_class) { pictures_total = 1024; // the max total b_download_seed = false; } // download all pictures and seeds of topics cout << "Download the pictures and seeds of topics: " << endl; unsigned parsed_topics_cnt = 0; for (unsigned i = 0; i < (valid_topics_urls_list.size() / threads_total); ++i) { vector<thread> threads_list; for (unsigned j = 0; j < threads_total; ++j) { ++parsed_topics_cnt; threads_list.push_back(thread( &downloadTopicPicsAndSeed, ref(valid_topics_urls_list[i * threads_total + j]), ref(getNextProxyAddr(proxy_addrs_list)), ref(path), timeout_download_pic, pictures_total, b_download_seed, true )); } for (auto& e : threads_list) { if (e.joinable()) { e.join(); } } if (!threads_list.empty()) { cout << setprecision(1) << setiosflags(ios::fixed); cout << " " << RichTxt::bold_on << RichTxt::underline_on << "<---- " << 100.0 * parsed_topics_cnt / valid_topics_urls_list.size() << "% ---->" << RichTxt::underline_off << RichTxt::bold_off << endl; cout << resetiosflags(ios::fixed); } } vector<thread> threads_list; for (unsigned i = (valid_topics_urls_list.size() / threads_total) * threads_total; i < valid_topics_urls_list.size(); ++i) { ++parsed_topics_cnt; threads_list.push_back(thread( &downloadTopicPicsAndSeed, ref(valid_topics_urls_list[i]), ref(getNextProxyAddr(proxy_addrs_list)), ref(path), timeout_download_pic, pictures_total, b_download_seed, true )); } for (auto& e : threads_list) { if (e.joinable()) { e.join(); } } if (!threads_list.empty()) { cout << setprecision(1) << setiosflags(ios::fixed); cout << " " << RichTxt::bold_on << RichTxt::underline_on << "<---- " << 100.0 * parsed_topics_cnt / valid_topics_urls_list.size() << "% ---->" << RichTxt::underline_off << RichTxt::bold_off << endl; cout << resetiosflags(ios::fixed); } cout << endl; cout << "Hey kiddo, your hot babes " << path << ", enjoy it! " << endl; } Caoliu::~Caoliu () { ; }
15,001
C++
.cpp
345
30.884058
139
0.528963
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,505
JandownSeedWebpage.cpp
yangyangwithgnu_hardseed/src/lib/self/JandownSeedWebpage.cpp
// last modified #include "JandownSeedWebpage.h" #include <iostream> #include <algorithm> #include <unistd.h> #include "../helper/Misc.h" using namespace std; static bool parsePostMultiSections ( const string& webpage_txt, vector<pair<string, string>>& post_sections_list ) { // parse the code section static const string keyword_code_section_begin("<input type=text name=code size=30 value="); static const string keyword_code_section_end(" >"); const pair<string, size_t>& pair_tmp = fetchStringBetweenKeywords( webpage_txt, keyword_code_section_begin, keyword_code_section_end ); const string& ref_content = pair_tmp.first; if (ref_content.empty()) { cerr << "WARNING! parsePostMultiSections() CANNOT find the keyword " << "\"" << keyword_code_section_begin << "\"" << " and " << "\"" << keyword_code_section_end << "\"" << endl; return(false); } post_sections_list.push_back(make_pair("code", ref_content)); return(true); } // seed fetch URL. http://www.jandown.com/ and http://www6.mimima.com/ are // the same one website, on the other word, from http://www.jandown.com/abcd // download the seed file same as from http://www6.mimima.com/abcd, so, I need // just ONE fetch URL JandownSeedWebpage::JandownSeedWebpage (const string& url, const string& proxy_addr) : SeedWebpage(url, proxy_addr, "http://www.jandown.com/fetch.php", parsePostMultiSections) { ; } JandownSeedWebpage::~JandownSeedWebpage () { ; }
1,680
C++
.cpp
40
34.3
98
0.626225
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,506
TopicWebpage.cpp
yangyangwithgnu_hardseed/src/lib/self/TopicWebpage.cpp
// last modified #include "TopicWebpage.h" #include <iostream> #include <sstream> #include "../helper/Misc.h" #include <unistd.h> using namespace std; TopicWebpage::TopicWebpage ( const string& url, ParsePicturesUrls parsePicturesUrls, ParseSeedUrl parseSeedUrl, const string& proxy_addr, const string& src_charset, const string& dest_charset ) : Webpage(url, "", proxy_addr) { if (!isLoaded()) { return; } // charset convert if (!src_charset.empty() && !dest_charset.empty()) { convertCharset(src_charset, dest_charset); } // parse the URLs of av pictures if (!parsePicturesUrls(getTxt(), pictures_urls_list_)) { //cerr << "WARNING! parsePicturesUrls() failure from " << url << endl; ; } // parse the URLs of seed if (!parseSeedUrl(getTxt(), seed_url_)) { //cerr << "WARNING! parseSeedUrl() failure from " << url << endl; ; } } TopicWebpage::~TopicWebpage () { ; } const vector<string>& TopicWebpage::getPicturesUrlsList (void) const { return(pictures_urls_list_); } const string& TopicWebpage::getSeedUrl (void) const { return(seed_url_); } // the name rule of pictures: topictitle-0.jpg, topictitle-1.jpg, topictitle-[x].jpg bool TopicWebpage::downloadAllPictures ( const string& path, const string& base_name, unsigned timeout_download_pic, vector<string>& fail_download_pics_urls_list, unsigned pictures_max_num ) { fail_download_pics_urls_list.clear(); for ( unsigned i = 0, sucess_cnt = 0; i < pictures_urls_list_.size() && sucess_cnt < pictures_max_num; ++i ) { const string& picture_url = pictures_urls_list_[i]; // make picture postfix name //string postfix_name("jpeg"); // sometime get the remote filetype failure, so I set the default postfix string postfix_name(""); static const unsigned get_remote_filetype_retry_times = 2; static const unsigned get_remote_filetype_sleep_second = 2; for (unsigned j = 0; j < get_remote_filetype_retry_times; ++j) { const string& tmp = getRemoteFiletype(picture_url); static const string keyword("image/"); const auto pos = tmp.find(keyword); if (string::npos != pos) { postfix_name = tmp.substr(pos + keyword.size()); break; } sleep(get_remote_filetype_sleep_second); } // neither gif (because gifs almost be AD) nor cannot get the file type, ignore if ("gif" == postfix_name || "" == postfix_name) { continue; } // download pic const string& pic_filename = path + "/" + base_name + "-" + convNumToStr(sucess_cnt) + "." + postfix_name; if (downloadFile(picture_url, pic_filename, "", timeout_download_pic)) { ++sucess_cnt; continue; } //cerr << "WARNING! CANNOT download " << pictures_urls_list_[i] << endl; fail_download_pics_urls_list.push_back(pictures_urls_list_[i]); remove(pic_filename.c_str()); } return(fail_download_pics_urls_list.empty()); }
3,464
C++
.cpp
91
28.692308
114
0.577477
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,507
SeedWebpage.cpp
yangyangwithgnu_hardseed/src/lib/self/SeedWebpage.cpp
// last modified #include "SeedWebpage.h" #include <iostream> #include <algorithm> #include <unistd.h> using namespace std; SeedWebpage::SeedWebpage ( const string& url, const string& proxy_addr, const string& post_url, ParsePostMultiSections parsePostMultiSections ) : Webpage(url, "", proxy_addr), post_url_(post_url) { if (!isLoaded()) { cerr << "WARNING! SeedWebpage::SeedWebpage() CANNOT load webpage \"" << url << "\"" << endl; return; } // parse the post method multi sections parsePostMultiSections(getTxt(), post_sections_list_); } SeedWebpage::~SeedWebpage () { ; } // this is a multipart/formdata style HTTP post method bool SeedWebpage::downloadSeed (const string& path, const string& base_name) { if (post_sections_list_.empty()) { return(false); } // make seed name static const string seed_postfix(".torrent"); string seed_filename = path + "/" + base_name + seed_postfix; return(submitMultiPost(post_url_, seed_filename, post_sections_list_)); }
1,139
C++
.cpp
36
25.722222
76
0.63678
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,508
RmdownSeedWebpage.cpp
yangyangwithgnu_hardseed/src/lib/self/RmdownSeedWebpage.cpp
// last modified #include "RmdownSeedWebpage.h" #include <iostream> #include <algorithm> #include <unistd.h> #include "../helper/Misc.h" using namespace std; static bool parsePostMultiSections ( const string& webpage_txt, vector<pair<string, string>>& post_sections_list ) { // parse the ref section static const string& keyword_ref_section_begin("<INPUT size=58 name=\"ref\" value=\""); static const string& keyword_ref_section_end("\""); const pair<string, size_t>& pair_tmp = fetchStringBetweenKeywords( webpage_txt, keyword_ref_section_begin, keyword_ref_section_end ); const string& ref_content = pair_tmp.first; if (ref_content.empty()) { cerr << "WARNING! parsePostMultiSections() CANNOT find the keyword " << "\"" << keyword_ref_section_begin << "\"" << " and " << "\"" << keyword_ref_section_end << "\"" << endl; return(false); } post_sections_list.push_back(make_pair("ref", ref_content)); const auto keyword_ref_section_end_pos = pair_tmp.second; // parse the reff section static const string& keyword_reff_section_begin("value=\""); static const string& keyword_reff_section_end("\""); const pair<string, size_t>& pair_tmp2 = fetchStringBetweenKeywords( webpage_txt, keyword_reff_section_begin, keyword_reff_section_end, keyword_ref_section_end_pos ); const string& reff_content = pair_tmp2.first; if (reff_content.empty()) { cerr << "WARNING! parsePostMultiSections() CANNOT find the keyword " << "\"" << keyword_reff_section_begin << "\"" << " and " << "\"" << keyword_reff_section_end << "\"" << endl; return(false); } post_sections_list.push_back(make_pair("reff", reff_content)); return(true); } // seed fetch URL. http://www.rmdown.com/ and http://www.xunfs.com/ are // the same one website, on the other word, from http://www.rmdown.com/abcd // download the seed file same as from http://www.xunfs.com/abcd, so, I need // just ONE fetch URL RmdownSeedWebpage::RmdownSeedWebpage (const string& url, const string& proxy_addr) : SeedWebpage(url, proxy_addr, "http://www.rmdown.com/download.php", parsePostMultiSections) { ; } RmdownSeedWebpage::~RmdownSeedWebpage () { ; }
2,650
C++
.cpp
56
36.303571
101
0.576238
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,509
TopicsListWebpage.cpp
yangyangwithgnu_hardseed/src/lib/self/TopicsListWebpage.cpp
// last modified #include "TopicsListWebpage.h" #include <iostream> using namespace std; TopicsListWebpage::TopicsListWebpage ( const string& portal_url, const string& url, TopicsListWebpage::ParseTitlesAndUrls parseTitlesAndUrls, TopicsListWebpage::ParseNextpageUrl parseNextpageUrl, const string& proxy_addr, const string& src_charset, const string& dest_charset ) : Webpage(url, "", proxy_addr, 16, 4, 4), portal_url_(portal_url) { if (!isLoaded()) { return; } // charset convert if (!src_charset.empty() && !dest_charset.empty()) { convertCharset(src_charset, dest_charset); } // parse the URLs and titles of all topics on topicslist webpage const string& webpage_txt = getTxt(); parseTitlesAndUrls(webpage_txt, portal_url_, titles_and_urls_list_); // unescape html for title for (auto& e : titles_and_urls_list_) { string& title = e.first; title = unescapeHtml(title); } // parse the next topicslist webpage URL parseNextpageUrl(webpage_txt, portal_url_, nextpage_url_); } TopicsListWebpage::~TopicsListWebpage () { ; } // if there is no more topicslist page, return empty string const string& TopicsListWebpage::getNextpageUrl (void) const { return(nextpage_url_); } // first title, second url const vector<pair<string, string>>& TopicsListWebpage::getTitlesAndUrlsList (void) const { return(titles_and_urls_list_); } const string& TopicsListWebpage::getPortalWebpageUrl (void) const { return(portal_url_); }
1,774
C++
.cpp
53
25.698113
96
0.626245
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,510
Aicheng.cpp
yangyangwithgnu_hardseed/src/lib/self/Aicheng.cpp
// last modified #include "Aicheng.h" #include <iostream> #include <iomanip> #include <algorithm> #include <iterator> #include <thread> #include <mutex> #include <cstdlib> #include <unistd.h> #include "AichengTopicsListWebpage.h" #include "AichengTopicWebpage.h" #include "JandownSeedWebpage.h" #include "../helper/RichTxt.h" using namespace std; static mutex g_mtx; const string& Aicheng::getPortalWebpageUrl (void) const { return(portal_url_); } static const string& getTopicsListWebpagePartUrl (Aicheng::AvClass av_class) { static const string west_part_url("thread.php?fid=5"); static const string cartoon_part_url("thread.php?fid=6"); static const string asia_mosaicked_part_url("thread.php?fid=4"); static const string asia_non_mosaicked_part_url("thread.php?fid=16"); switch (av_class) { case Aicheng::west: return(west_part_url); case Aicheng::cartoon: return(cartoon_part_url); case Aicheng::asia_mosaicked: return(asia_mosaicked_part_url); case Aicheng::asia_non_mosaicked: return(asia_non_mosaicked_part_url); } } static const string getTopicsListWebpageUrl (const string& portal_url, Aicheng::AvClass av_class) { return(portal_url + getTopicsListWebpagePartUrl(av_class)); } static bool isThereInList ( const string& webpage_title, const vector<string>& ignore_keywords_list, string& which_keyword ) { for (const auto& e : ignore_keywords_list) { if (!e.empty() && string::npos != webpage_title.find(e)) { which_keyword = e; return(true); } } return(false); } static bool parseValidTopicsUrls ( Aicheng::AvClass av_class, const string& portal_url, const string& proxy_addr, unsigned range_begin, unsigned range_end, const vector<string>& hate_keywords_list, const vector<string>& like_keywords_list, vector<string>& valid_topics_urls_list, bool b_progress ) { valid_topics_urls_list.clear(); string current_url = getTopicsListWebpageUrl(portal_url, av_class); bool b_stop = false; unsigned topics_cnt = 0; while (!current_url.empty() && !b_stop) { AichengTopicsListWebpage aicheng_topicslist_webpage(portal_url, current_url, proxy_addr); if (!aicheng_topicslist_webpage.isLoaded()) { return(false); } const vector<pair<string, string>>& topics_title_and_url = aicheng_topicslist_webpage.getTitlesAndUrlsList(); for (const auto& e : topics_title_and_url) { if (++topics_cnt > range_end) { b_stop = true; break; } const string& topic_title = e.first; const string& topic_url = e.second; static const string o_flag(RichTxt::bold_on + "O" + RichTxt::bold_off); static const string x_flag("x"); // ignore the topics which do not in range if (topics_cnt < range_begin) { if (b_progress) { cout << x_flag << " " << flush; } continue; } // ignore the topics which contain hate keyword by user set string which_keyword; if (isThereInList(topic_title, hate_keywords_list, which_keyword)) { if (b_progress) { cout << x_flag << " " << flush; } continue; } // ignore the topics which do not contain like keyword by user set if ( !like_keywords_list.empty() && !isThereInList(topic_title, like_keywords_list, which_keyword) ) { if (b_progress) { cout << x_flag << " " << flush; } continue; } valid_topics_urls_list.push_back(topic_url); if (b_progress) { cout << o_flag << " " << flush; } } current_url = aicheng_topicslist_webpage.getNextpageUrl(); } return(true); } static void downloadTopicPicsAndSeed ( const string& topic_url, const string& proxy_addr, const string& path, unsigned timeout_download_pic, bool b_show_info ) { AichengTopicWebpage aicheng_topics_webpage(topic_url, proxy_addr); // ready for the basename of pictures and seed. // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> string base_name; // from topic title // 0) delete the web logo info; // 1) clear the "/" in topictitle string, if the "/" present in filename, // linux will treat it as directory, again, clear the "\" for windows; static const vector<string> keyword_logos_list = { " 亚洲无码区 bt下载 - powered by phpwind.net", " 亚洲有码区 bt下载 - powered by phpwind.net", " 欧美区 bt下载 - powered by phpwind.net", " 动漫区 bt下载 - powered by phpwind.net", "|亚洲无码区 - bt下载 爱城 bt下载 ", "亚洲无码区 - bt下载 爱城 bt下载 ", "|亚洲有码区 - bt下载 爱城 bt下载 ", "亚洲有码区 - bt下载 爱城 bt下载 ", "|动漫区 - bt下载 爱城 bt下载 ", "动漫区 - bt下载 爱城 bt下载 ", "|欧美区 - bt下载 爱城 bt下载 ", "欧美区 - bt下载 爱城 bt下载 " }; const string& topic_webpage_title = aicheng_topics_webpage.getTitle(); auto keyword_logo_pos = string::npos; for (const auto& f : keyword_logos_list) { keyword_logo_pos = topic_webpage_title.find(f); if (string::npos != keyword_logo_pos) { break; } } remove_copy_if( topic_webpage_title.cbegin(), (string::npos == keyword_logo_pos) ? topic_webpage_title.cend() : topic_webpage_title.cbegin() + (int)keyword_logo_pos, back_inserter(base_name), [] (char ch) {return( '|' == ch || // invalid chars in windows-style filename '/' == ch || '<' == ch || '>' == ch || '?' == ch || '*' == ch || ':' == ch || '\\' == ch );} ); // 2) the path + filename max length must less than pathconf(, _PC_NAME_MAX) const unsigned filename_max_length_without_postfix = (unsigned)pathconf(path.c_str(), _PC_NAME_MAX) - string("99").size() // picture number - string(".torrent").size(); if (base_name.size() >= filename_max_length_without_postfix) { // the filename too long to create file. the way as following doesn't work, case filename encoding error: // base_name.resize(filename_max_length_without_postfix - 1), because this is string on char not wstring on wchar. // there is another stupid way, random name from 'a' to 'z' base_name.resize(16); generate( base_name.begin(), base_name.end(), [] () {return('a' + rand() % ('z' - 'a'));} ); base_name = "(rename)" + base_name; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // download all pictures vector<string> fail_download_pics_urls_list; bool b_download_pics_success = aicheng_topics_webpage.downloadAllPictures( path, base_name, timeout_download_pic, fail_download_pics_urls_list, 32 ); // download seed bool b_downloaded_seed_success = false; if (!aicheng_topics_webpage.getSeedUrl().empty()) { JandownSeedWebpage jan_seed_webpage(aicheng_topics_webpage.getSeedUrl(), proxy_addr); b_downloaded_seed_success = jan_seed_webpage.downloadSeed(path, base_name); } // show result info if (!b_show_info) { return; } static const string success_info("success"); static const string fail_info = RichTxt::foreground_red + "failure" + RichTxt::reset_all; g_mtx.lock(); cout << " \"" << base_name << "\" - "; if (b_download_pics_success && b_downloaded_seed_success) { cout << success_info; } else { cout << fail_info << " (download error from " << topic_url << ". "; if (!b_download_pics_success) { cout << "pictures error: "; copy(fail_download_pics_urls_list.cbegin(), fail_download_pics_urls_list.cend(), ostream_iterator<const string&>(cout, ", ")); cout << "\b\b"; } if (!b_downloaded_seed_success) { if (!b_download_pics_success) { cout << "; "; } cout << "seed error: " << aicheng_topics_webpage.getSeedUrl(); } cout << ")"; } cout << endl; g_mtx.unlock(); } static const string& getNextProxyAddr (const vector<string>& proxy_addrs_list) { if (proxy_addrs_list.empty()) { static const string empty_str(""); return(empty_str); } static unsigned current_pos; if (current_pos >= proxy_addrs_list.size()) { current_pos = 0; } return(proxy_addrs_list[current_pos++]); } Aicheng::Aicheng ( const string& portal_url, AvClass av_class, const vector<string>& proxy_addrs_list, unsigned range_begin, unsigned range_end, const vector<string>& hate_keywords_list, const vector<string>& like_keywords_list, unsigned threads_total, unsigned timeout_download_pic, const string& path ) : portal_url_(portal_url) { // parse the URLs of valid topics by: range, hate keywords, like keywords cout << "Parse the URLs of topics from " << range_begin << " to " << range_end << ": " << flush; vector<string> valid_topics_urls_list; parseValidTopicsUrls( av_class, portal_url, getNextProxyAddr(proxy_addrs_list), range_begin, range_end, hate_keywords_list, like_keywords_list, valid_topics_urls_list, true ); if (valid_topics_urls_list.empty()) { cout << "(There is no topic which you like) " << endl; return; } cout << endl << endl; // download all pictures and seeds of topics cout << "Download the pictures and seeds of topics: " << endl; unsigned parsed_topics_cnt = 0; for (unsigned i = 0; i < (valid_topics_urls_list.size() / threads_total); ++i) { vector<thread> threads_list; for (unsigned j = 0; j < threads_total; ++j) { ++parsed_topics_cnt; threads_list.push_back(thread( &downloadTopicPicsAndSeed, ref(valid_topics_urls_list[i * threads_total + j]), ref(getNextProxyAddr(proxy_addrs_list)), ref(path), timeout_download_pic, true )); } for (auto& e : threads_list) { if (e.joinable()) { e.join(); } } if (!threads_list.empty()) { cout << setprecision(1) << setiosflags(ios::fixed); cout << " " << RichTxt::bold_on << RichTxt::underline_on << "<---- " << 100.0 * parsed_topics_cnt / valid_topics_urls_list.size() << "% ---->" << RichTxt::underline_off << RichTxt::bold_off << endl; cout << resetiosflags(ios::fixed); } } vector<thread> threads_list; for ( unsigned i = (valid_topics_urls_list.size() / threads_total) * threads_total; i < valid_topics_urls_list.size(); ++i ) { ++parsed_topics_cnt; threads_list.push_back(thread( &downloadTopicPicsAndSeed, ref(valid_topics_urls_list[i]), ref(getNextProxyAddr(proxy_addrs_list)), ref(path), timeout_download_pic, true )); } for (auto& e : threads_list) { if (e.joinable()) { e.join(); } } if (!threads_list.empty()) { cout << setprecision(1) << setiosflags(ios::fixed); cout << " " << RichTxt::bold_on << RichTxt::underline_on << "<---- " << 100.0 * parsed_topics_cnt / valid_topics_urls_list.size() << "% ---->" << RichTxt::underline_off << RichTxt::bold_off << endl; cout << resetiosflags(ios::fixed); } cout << endl; cout << "Hey kiddo, your hot babes " << path << ", enjoy it! " << endl; } Aicheng::~Aicheng () { ; }
14,209
C++
.cpp
316
30.03481
139
0.499079
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,511
CaoliuTopicWebpage.cpp
yangyangwithgnu_hardseed/src/lib/self/CaoliuTopicWebpage.cpp
// last modified #include "CaoliuTopicWebpage.h" #include <iostream> #include <iterator> #include <algorithm> #include "../helper/Misc.h" using namespace std; static bool parsePicturesUrlsHelper ( const string& webpage_txt, vector<string>& pictures_urls_list, const string& keyword_begin, const string& keyword_end ) { bool b_ok = false; size_t start_pos = 0; while (true) { // parse picture URL const pair<string, size_t>& pair_tmp = fetchStringBetweenKeywords( webpage_txt, keyword_begin, keyword_end, start_pos ); string pic_url = pair_tmp.first; if (pic_url.empty()) { break; } start_pos = pair_tmp.second; b_ok = true; // there are some bad picture-webspaces and logo pci, ignore them bool b_ignore_url = false; static const vector<string> ignore_urls_keywords_list = { "iceimg.com", "picuphost.com", // caoliu froum selfie member's logo. // http://ww4.sinaimg.cn/mw690/005uMz33gw1egsm41zq6qj30f80b4gm9.jpg // >>>> "005uMz33gw1eh3a1r6ak0j30d005zt98.jpg", "005uMz33gw1egsm41zq6qj30f80b4gm9.jpg", // <<<< }; for (const auto& e : ignore_urls_keywords_list) { if (string::npos != pic_url.find(e)) { b_ignore_url = true; break; } } if (b_ignore_url) { continue; } // save the picture URL pictures_urls_list.push_back(pic_url); } return(b_ok); } static bool parsePicturesUrls (const string& webpage_txt, vector<string>& pictures_urls_list) { pictures_urls_list.clear(); // just parse the toptip static const string keyword_toptip_begin("<b>本頁主題:</b>"); static const string keyword_toptip_end("[樓主]</a></span>"); const pair<string, size_t>& pair_tmp = fetchStringBetweenKeywords( webpage_txt, keyword_toptip_begin, keyword_toptip_end ); string toptip = pair_tmp.first; if (toptip.empty()) { cerr << "ERROR! there is no toptip. " << endl; return(false); } // the list may be on the webpage at the same time static const vector<pair<string, string>> begin_and_end_keywords_list = { make_pair("<img src='", "'"), make_pair("input type='image' src='", "'"), make_pair("<input src='", "'") }; bool b_ok = false; for (const auto& e : begin_and_end_keywords_list) { if (parsePicturesUrlsHelper(toptip, pictures_urls_list, e.first, e.second)) { b_ok = true; } } return(b_ok); } static bool parseSeedUrl (const string& webpage_txt, string& seed_url) { static const vector<string> keywords_seed_begin_list = { "http://www.rmdown.com/link.php?hash=", "http://rmdown.com/link.php?hash=", "http://www.xunfs.com/link.php?hash=", "http://xunfs.com/link.php?hash=" }; for (const auto& e : keywords_seed_begin_list) { const string& keyword_seed_begin = e; static const string keyword_seed_end("</a>"); const pair<string, size_t>& pair_tmp = fetchStringBetweenKeywords( webpage_txt, keyword_seed_begin, keyword_seed_end ); if (!pair_tmp.first.empty()) { seed_url = keyword_seed_begin + pair_tmp.first; return(true); } } return(false); } CaoliuTopicWebpage::CaoliuTopicWebpage (const string& url, const string& proxy_addr) : TopicWebpage(url, parsePicturesUrls, parseSeedUrl, proxy_addr, "gbk", "UTF-8") { ; } CaoliuTopicWebpage::~CaoliuTopicWebpage () { ; }
5,051
C++
.cpp
109
26.87156
133
0.444672
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,512
AichengTopicsListWebpage.cpp
yangyangwithgnu_hardseed/src/lib/self/AichengTopicsListWebpage.cpp
// last modified #include "AichengTopicsListWebpage.h" #include <iostream> #include <cstdlib> #include "../helper/Misc.h" using namespace std; static bool parseTitlesAndUrls ( const string& webpage_txt, const string& portal_url, vector<pair<string, string>>& titles_and_urls_list ) { const unsigned size_back = titles_and_urls_list.size(); const auto topics_list_txt_pos = webpage_txt.find(R"(style="border-top:0">普通主题</td></tr>)"); size_t keyword_topic_url_begin_pos = ((string::npos == topics_list_txt_pos) ? 0 : topics_list_txt_pos); size_t keyword_topic_url_end_pos = 0; while (true) { // parse topic URL static const string keyword_topic_url_begin("<h3><a href=\""); static const string keyword_topic_url_end("\""); const pair<string, size_t>& pair_url = fetchStringBetweenKeywords( webpage_txt, keyword_topic_url_begin, keyword_topic_url_end, keyword_topic_url_begin_pos ); const string& topic_url_part = pair_url.first; if (topic_url_part.empty()) { break; } const string topic_url = portal_url + topic_url_part; keyword_topic_url_end_pos = pair_url.second; // parse topic title static const string keyword_topic_title_begin("target=_blank>"); static const string keyword_topic_title_end("</a></h3>"); const pair<string, size_t>& pair_title = fetchStringBetweenKeywords( webpage_txt, keyword_topic_title_begin, keyword_topic_title_end, //keyword_topic_url_end_pos - keyword_topic_title_begin.size() ); keyword_topic_url_end_pos ); const string& topic_title = pair_title.first; keyword_topic_url_begin_pos = pair_title.second; // save url and title of the topic titles_and_urls_list.push_back(make_pair(topic_title, topic_url)); } return(titles_and_urls_list.size() > size_back); } static bool parseNextpageUrl (const string& webpage_txt, const string& portal_url, string& nextpage_url) { nextpage_url.empty(); static const string keyword_nextpage_begin("</b><a href=\""); static const string keyword_nextpage_end("\">"); const string& nextpage_url_part = fetchStringBetweenKeywords( webpage_txt, keyword_nextpage_begin, keyword_nextpage_end ).first; if (nextpage_url_part.empty()) { return(false); } // portal_url 中多了 "/bt" nextpage_url = string(portal_url.cbegin(), portal_url.cend() - (const int)string("/bt").length()) + nextpage_url_part; return(true); } AichengTopicsListWebpage::AichengTopicsListWebpage (const string& portal_url, const string& url, const string& proxy_addr) : TopicsListWebpage(portal_url, url, parseTitlesAndUrls, parseNextpageUrl, proxy_addr, "gbk", "UTF-8") { ; } AichengTopicsListWebpage::~AichengTopicsListWebpage () { ; }
3,554
C++
.cpp
69
36.086957
142
0.551121
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,513
AichengTopicWebpage.cpp
yangyangwithgnu_hardseed/src/lib/self/AichengTopicWebpage.cpp
// last modified #include "AichengTopicWebpage.h" #include <iostream> #include <iterator> #include <algorithm> #include "../helper/Misc.h" using namespace std; static bool parsePicturesUrlsHelper ( const string& webpage_txt, vector<string>& pictures_urls_list, const string& keyword_begin, const string& keyword_end ) { bool b_ok = false; size_t keyword_pic_begin_pos = 0; while (true) { // parse picture URL const pair<string, size_t>& pair_tmp = fetchStringBetweenKeywords( webpage_txt, keyword_begin, keyword_end, keyword_pic_begin_pos ); string pic_url = pair_tmp.first; if (pic_url.empty()) { break; } keyword_pic_begin_pos = pair_tmp.second; b_ok = true; // there are some bad picture-webspaces and logo pci, ignore them bool b_ignore_url = false; static const vector<string> ignore_urls_keywords_list = { "iceimg.com", }; for (const auto& e : ignore_urls_keywords_list) { if (string::npos != pic_url.find(e)) { b_ignore_url = true; break; } } if (b_ignore_url) { continue; } // convert https to http static const string keyword_https("https://"); const auto https_pos = pic_url.find(keyword_https); if (string::npos != https_pos) { static const string keyword_http("http://"); pic_url.replace(https_pos, keyword_https.size(), keyword_http); } // save the picture URL pictures_urls_list.push_back(pic_url); } return(b_ok); } static bool parsePicturesUrls (const string& webpage_txt, vector<string>& pictures_urls_list) { pictures_urls_list.clear(); // just parse the toptip static const string keyword_toptip_begin("<tr><td class=\"h\"><b>本页主题:</b>"); static const string keyword_toptip_end(">[楼 主]</a></span>"); const pair<string, size_t>& pair_tmp = fetchStringBetweenKeywords( webpage_txt, keyword_toptip_begin, keyword_toptip_end ); string toptip = pair_tmp.first; if (toptip.empty()) { cerr << "ERROR! there is no toptip. " << endl; return(false); } // the list may be on the webpage at the same time static const vector<pair<string, string>> begin_and_end_keywords_list = { make_pair("<img src=\"", "\""), make_pair("<img src='", "'"), make_pair("<img src=", " ") }; bool b_ok = false; for (const auto& e : begin_and_end_keywords_list) { if (parsePicturesUrlsHelper(toptip, pictures_urls_list, e.first, e.second)) { b_ok = true; } } return(b_ok); } static bool parseSeedUrl (const string& webpage_txt, string& seed_url) { static const vector<string> keywords_seed_begin_list = { "http://www.jandown.com", "http://jandown.com", "http://www6.mimima.com", "http://mimima.com" }; const auto body_pos = webpage_txt.find("<body>"); if (string::npos == body_pos) { //cerr << "warning! parseseedurl() cannot find the keyword \"<body>\"" << endl; return(false); } const string& body = webpage_txt.substr(body_pos); for (const auto& e : keywords_seed_begin_list) { const string& keyword_seed_begin = e; static const string keyword_seed_end("\""); const pair<string, size_t>& pair_tmp = fetchStringBetweenKeywords( body, keyword_seed_begin, keyword_seed_end ); if (!pair_tmp.first.empty()) { seed_url = keyword_seed_begin + pair_tmp.first; return(true); } } return(false); } AichengTopicWebpage::AichengTopicWebpage (const string& url, const string& proxy_addr) : TopicWebpage(url, parsePicturesUrls, parseSeedUrl, proxy_addr, "gbk", "UTF-8") { ; } AichengTopicWebpage::~AichengTopicWebpage () { ; }
4,956
C++
.cpp
115
27.704348
110
0.489001
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,514
CaoliuTopicsListWebpage.cpp
yangyangwithgnu_hardseed/src/lib/self/CaoliuTopicsListWebpage.cpp
// last modified #include "CaoliuTopicsListWebpage.h" #include <iostream> #include <cstdlib> #include "../helper/Misc.h" using namespace std; static bool parseTitlesAndUrls ( const string& webpage_txt, const string& portal_url, vector<pair<string, string>>& titles_and_urls_list ) { const unsigned size_back = titles_and_urls_list.size(); size_t keyword_topic_url_begin_pos = 0, keyword_topic_url_end_pos = 0; keyword_topic_url_begin_pos = webpage_txt.find("普通主題"); if (string::npos == keyword_topic_url_begin_pos) { keyword_topic_url_begin_pos = 0; } while (true) { // parse topic URL static const string keyword_topic_url_begin("<h3><a href=\""); static const string keyword_topic_url_begin2("htm_data"); static const string keyword_topic_url_end("\""); const pair<string, size_t>& pair_url = fetchStringBetweenKeywords( webpage_txt, keyword_topic_url_begin + keyword_topic_url_begin2, keyword_topic_url_end, keyword_topic_url_begin_pos ); const string& topic_url_part = pair_url.first; if (topic_url_part.empty()) { break; } const string& topic_url = portal_url + keyword_topic_url_begin2 + topic_url_part; keyword_topic_url_end_pos = pair_url.second; // parse topic title static const string keyword_topic_title_begin("id=\"\">"); static const string keyword_topic_title_end("</a></h3>"); const pair<string, size_t>& pair_title = fetchStringBetweenKeywords( webpage_txt, keyword_topic_title_begin, keyword_topic_title_end, keyword_topic_url_end_pos ); const string& topic_title = pair_title.first; keyword_topic_url_begin_pos = pair_title.second; // save url and title of the topic titles_and_urls_list.push_back(make_pair(topic_title, topic_url)); } return(titles_and_urls_list.size() > size_back); } static bool parseNextpageUrl (const string& webpage_txt, const string& portal_url, string& nextpage_url) { nextpage_url.empty(); static const string keyword_nextpage("下一頁"); const auto keyword_nextpage_pos = webpage_txt.find(keyword_nextpage); if (string::npos == keyword_nextpage_pos) { return(false); } static const string keyword_href("<a href=\""); const auto keyword_href_pos = webpage_txt.rfind(keyword_href, keyword_nextpage_pos); if (string::npos == keyword_href_pos) { cerr << "WARNING! parseNextpageUrl() cannot find the keyword " << keyword_href << ". " << endl; return(false); } const auto nextpage_suburl_begin_pos = keyword_href_pos + keyword_href.size(); const auto nextpage_suburl_end_pos = webpage_txt.find("\"", nextpage_suburl_begin_pos); if (string::npos == nextpage_suburl_end_pos) { cerr << "WARNING! parseNextpageUrl() cannot find the keyword '. " << endl; return(false); } nextpage_url = portal_url + webpage_txt.substr(nextpage_suburl_begin_pos, nextpage_suburl_end_pos - nextpage_suburl_begin_pos); return(true); } CaoliuTopicsListWebpage::CaoliuTopicsListWebpage (const string& portal_url, const string& url, const string& proxy_addr) : TopicsListWebpage(portal_url, url, parseTitlesAndUrls, parseNextpageUrl, proxy_addr, "gbk", "UTF-8") { ; } CaoliuTopicsListWebpage::~CaoliuTopicsListWebpage () { ; }
3,921
C++
.cpp
80
36.975
126
0.593082
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
15,518
RichTxt.h
yangyangwithgnu_hardseed/src/lib/helper/RichTxt.h
// last modified #pragma once #include <string> using std::string; namespace RichTxt { // bold static const string bold_on("\x1b[1m"); static const string bold_off("\x1b[21m"); // italic static const string italic_on("\x1b[3m"); static const string italic_off("\x1b[23m"); // underline static const string underline_on("\x1b[4m"); static const string underline_off("\x1b[24m"); // hide static const string hide_on("\x1b[8m"); static const string hide_off("\x1b[28m"); // deletline static const string deletline_on("\x1b[9m"); static const string deletline_off("\x1b[29m"); // foreground static const string foreground_black("\x1b[30m"); static const string foreground_red("\x1b[31m"); static const string foreground_green("\x1b[32m"); static const string foreground_yellow("\x1b[33m"); static const string foreground_blue("\x1b[34m"); static const string foreground_magenta("\x1b[35m"); static const string foreground_cyan("\x1b[36m"); static const string foreground_white("\x1b[37m"); // background static const string background_black("\x1b[40m"); static const string background_red("\x1b[41m"); static const string background_green("\x1b[42m"); static const string background_yellow("\x1b[43m"); static const string background_blue("\x1b[44m"); static const string background_magenta("\x1b[45m"); static const string background_cyan("\x1b[46m"); static const string background_white("\x1b[47m"); // reset all static const string reset_all("\x1b[0m"); }; // normal usage: // 0) cout << "email: " << RichTxt::bold_on << "yangyang.gnu@gmail.com" << RichTxt::bold_off << endl; // 1) string name("yangyang.gnu"); string name_italic = RichTxt::italic_on + RichTxt::background_green + name + RichTxt::italic_off;
1,863
C++
.h
45
36.977778
132
0.687535
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,521
Time.h
yangyangwithgnu_hardseed/src/lib/helper/Time.h
// last modified #pragma once #include <string> using std::string; class Time { public: Time (); virtual ~Time (); unsigned getYear (void) const; string getYear (unsigned digits) const; unsigned getMonth (void) const; string getMonth (unsigned digits) const; unsigned getDayInWeek (void) const; string getDayInWeek (bool b_abbr) const; unsigned getDayInMonth (void) const; string getDayInMonth (unsigned digits) const; unsigned getDayInYear (void) const; string getDayInYear (unsigned digits) const; unsigned getHour (void) const; string getHour (unsigned digits) const; unsigned getMinute (void) const; string getMinute (unsigned digits) const; unsigned getSecond (void) const; string getSecond (unsigned digits) const; private: unsigned year_; unsigned month_; unsigned day_in_month_; unsigned day_in_week_; unsigned day_in_year_; unsigned hour_; unsigned minute_; unsigned second_; };
1,165
C++
.h
35
24.371429
53
0.64239
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
15,522
AichengTopicWebpage.h
yangyangwithgnu_hardseed/src/lib/self/AichengTopicWebpage.h
// last modified #pragma once #include <string> #include <vector> #include "TopicWebpage.h" using std::string; using std::vector; class AichengTopicWebpage : public TopicWebpage { public: AichengTopicWebpage (const string& url, const string& proxy_addr); virtual ~AichengTopicWebpage (); };
318
C++
.h
13
21.384615
74
0.745819
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,523
Caoliu.h
yangyangwithgnu_hardseed/src/lib/self/Caoliu.h
// last modified #pragma once #include <string> #include <vector> using std::string; using std::vector; class Caoliu { public: enum AvClass { west_reposted, cartoon_reposted, asia_mosaicked_reposted, asia_non_mosaicked_reposted, west_original, cartoon_original, asia_mosaicked_original, asia_non_mosaicked_original, selfie }; public: Caoliu ( const string& portal_url, AvClass av_class, const vector<string>& proxy_addrs_list, unsigned range_begin, unsigned range_end, const vector<string>& hate_keywords_list, const vector<string>& like_keywords_list, unsigned threads_total, unsigned timeout_download_pic, const string& path ); virtual ~Caoliu (); const string& getPortalWebpageUrl (void) const; private: const string portal_url_; };
989
C++
.h
27
26.259259
109
0.604873
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,524
AichengTopicsListWebpage.h
yangyangwithgnu_hardseed/src/lib/self/AichengTopicsListWebpage.h
// last modified #pragma once #include <string> #include <vector> #include "TopicsListWebpage.h" using std::string; using std::vector; class AichengTopicsListWebpage : public TopicsListWebpage { public: AichengTopicsListWebpage (const string& portal_url, const string& url, const string& proxy_addr); virtual ~AichengTopicsListWebpage (); };
368
C++
.h
13
25.307692
105
0.765714
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,525
TopicsListWebpage.h
yangyangwithgnu_hardseed/src/lib/self/TopicsListWebpage.h
// last modified #pragma once #include <string> #include <vector> #include "../helper/Webpage.h" using std::string; using std::vector; using std::pair; class TopicsListWebpage : public Webpage { public: // callback function for parse titles and URLs of topics typedef bool (*ParseTitlesAndUrls) ( const string& webpage_txt, const string& portal_url, vector<pair<string, string>>& titles_and_urls_list ); // callback function for parse next topicslist URL typedef bool (*ParseNextpageUrl) ( const string& webpage_txt, const string& portal_url, string& nextpage_url ); public: TopicsListWebpage ( const string& portal_url, const string& url, ParseTitlesAndUrls parseTitlesAndUrls, ParseNextpageUrl parseNextpageUrl, const string& proxy_addr = "", const string& src_charset = "", const string& dest_charset = "" ); virtual ~TopicsListWebpage (); const vector<pair<string, string>>& getTitlesAndUrlsList (void) const; const string& getNextpageUrl (void) const; const string& getPortalWebpageUrl (void) const; private: vector<pair<string, string>> titles_and_urls_list_; string nextpage_url_; const string portal_url_; };
1,582
C++
.h
36
30.027778
99
0.555267
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,526
CaoliuTopicWebpage.h
yangyangwithgnu_hardseed/src/lib/self/CaoliuTopicWebpage.h
// last modified #pragma once #include <string> #include <vector> #include "TopicWebpage.h" using std::string; using std::vector; class CaoliuTopicWebpage : public TopicWebpage { public: CaoliuTopicWebpage (const string& url, const string& proxy_addr); virtual ~CaoliuTopicWebpage (); };
315
C++
.h
13
21.153846
73
0.743243
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,527
RmdownSeedWebpage.h
yangyangwithgnu_hardseed/src/lib/self/RmdownSeedWebpage.h
// last modified #pragma once #include <string> #include "SeedWebpage.h" using std::string; class RmdownSeedWebpage : public SeedWebpage { public: RmdownSeedWebpage (const string& url, const string& proxy_addr); virtual ~RmdownSeedWebpage (); };
272
C++
.h
11
21.363636
72
0.734375
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,528
JandownSeedWebpage.h
yangyangwithgnu_hardseed/src/lib/self/JandownSeedWebpage.h
// last modified #pragma once #include <string> #include "SeedWebpage.h" using std::string; class JandownSeedWebpage : public SeedWebpage { public: JandownSeedWebpage (const string& url, const string& proxy_addr); virtual ~JandownSeedWebpage (); };
275
C++
.h
11
21.636364
73
0.737452
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,529
TopicWebpage.h
yangyangwithgnu_hardseed/src/lib/self/TopicWebpage.h
// last modified #pragma once #include <string> #include <vector> #include "../helper/Webpage.h" using std::string; using std::vector; class TopicWebpage : public Webpage { public: // callback function for parse the URLs of av pictures typedef bool (*ParsePicturesUrls) (const string& webpage_txt, vector<string>& pictures_urls_list); // callback function for parse the URLs of seed typedef bool (*ParseSeedUrl) (const string& webpage_txt, string& seed_url); public: TopicWebpage ( const string& url, ParsePicturesUrls parsePicturesUrls, ParseSeedUrl parseSeedUrl, const string& proxy_addr, const string& src_charset, const string& dest_charset ); virtual ~TopicWebpage (); const string& getSeedUrl (void) const; const vector<string>& getPicturesUrlsList (void) const; bool downloadAllPictures ( const string& path, const string& base_name, unsigned timeout_download_pic, vector<string>& fail_download_pics_urls_list, unsigned pictures_max_num = 32 ); private: string seed_url_; vector<string> pictures_urls_list_; };
1,384
C++
.h
33
29.848485
107
0.584512
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,530
CaoliuTopicsListWebpage.h
yangyangwithgnu_hardseed/src/lib/self/CaoliuTopicsListWebpage.h
// last modified #pragma once #include <string> #include <vector> #include "TopicsListWebpage.h" using std::string; using std::vector; class CaoliuTopicsListWebpage : public TopicsListWebpage { public: CaoliuTopicsListWebpage (const string& portal_url, const string& url, const string& proxy_addr); virtual ~CaoliuTopicsListWebpage (); };
365
C++
.h
13
25.076923
104
0.763689
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,531
Aicheng.h
yangyangwithgnu_hardseed/src/lib/self/Aicheng.h
// last modified #pragma once #include <string> #include <vector> using std::string; using std::vector; class Aicheng { public: enum AvClass {west, cartoon, asia_mosaicked, asia_non_mosaicked}; public: Aicheng ( const string& portal_url, AvClass av_class, const vector<string>& proxy_addrs_list, unsigned range_begin, unsigned range_end, const vector<string>& hate_keywords_list, const vector<string>& like_keywords_list, unsigned threads_total, unsigned timeout_download_pic, const string& path ); virtual ~Aicheng (); const string& getPortalWebpageUrl (void) const; private: const string portal_url_; };
821
C++
.h
25
23.24
73
0.596401
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,532
SeedWebpage.h
yangyangwithgnu_hardseed/src/lib/self/SeedWebpage.h
// last modified #pragma once #include <string> #include <vector> #include "../helper/Webpage.h" using std::string; using std::vector; using std::pair; class SeedWebpage : public Webpage { public: // callback function for parse the multi sections of post typedef bool (*ParsePostMultiSections) ( const string& webpage_txt, vector<pair<string, string>>& post_sections_list ); public: SeedWebpage ( const string& url, const string& proxy_addr, const string& post_url, ParsePostMultiSections parsePostMultiSections ); virtual ~SeedWebpage (); bool downloadSeed (const string& path, const string& base_name); private: const string post_url_; vector<pair<string, string>> post_sections_list_; };
885
C++
.h
25
26.64
101
0.616647
yangyangwithgnu/hardseed
9,271
1,830
36
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,534
main.cpp
shadps4-emu_shadPS4/src/main.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <fmt/core.h> #include "common/memory_patcher.h" #include "emulator.h" #ifdef _WIN32 #include <windows.h> #endif int main(int argc, char* argv[]) { #ifdef _WIN32 SetConsoleOutputCP(CP_UTF8); #endif if (argc == 1) { fmt::print("Usage: {} <elf or eboot.bin path>\n", argv[0]); return -1; } // check if eboot file exists if (!std::filesystem::exists(argv[1])) { fmt::print("Eboot.bin file not found\n"); return -1; } for (int i = 0; i < argc; i++) { std::string curArg = argv[i]; if (curArg == "-p") { std::string patchFile = argv[i + 1]; MemoryPatcher::patchFile = patchFile; } } Core::Emulator emulator; emulator.Run(argv[1]); return 0; }
889
C++
.cpp
32
22.6875
67
0.603529
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,535
emulator.cpp
shadps4-emu_shadPS4/src/emulator.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <fmt/core.h> #include "common/config.h" #include "common/debug.h" #include "common/logging/backend.h" #include "common/logging/log.h" #ifdef ENABLE_QT_GUI #include <QtCore> #include "common/memory_patcher.h" #endif #include "common/assert.h" #ifdef ENABLE_DISCORD_RPC #include "common/discord_rpc_handler.h" #endif #include "common/elf_info.h" #include "common/ntapi.h" #include "common/path_util.h" #include "common/polyfill_thread.h" #include "common/scm_rev.h" #include "common/singleton.h" #include "common/version.h" #include "core/file_format/playgo_chunk.h" #include "core/file_format/psf.h" #include "core/file_format/splash.h" #include "core/file_format/trp.h" #include "core/file_sys/fs.h" #include "core/libraries/disc_map/disc_map.h" #include "core/libraries/fiber/fiber.h" #include "core/libraries/kernel/thread_management.h" #include "core/libraries/libc_internal/libc_internal.h" #include "core/libraries/libs.h" #include "core/libraries/ngs2/ngs2.h" #include "core/libraries/np_trophy/np_trophy.h" #include "core/libraries/rtc/rtc.h" #include "core/linker.h" #include "core/memory.h" #include "emulator.h" #include "video_core/renderdoc.h" Frontend::WindowSDL* g_window = nullptr; namespace Core { Emulator::Emulator() { // Read configuration file. const auto config_dir = Common::FS::GetUserPath(Common::FS::PathType::UserDir); Config::load(config_dir / "config.toml"); // Initialize NT API functions and set high priority #ifdef _WIN32 Common::NtApi::Initialize(); SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS); #endif // Start logger. Common::Log::Initialize(); Common::Log::Start(); LOG_INFO(Loader, "Starting shadps4 emulator v{} ", Common::VERSION); LOG_INFO(Loader, "Revision {}", Common::g_scm_rev); LOG_INFO(Loader, "Branch {}", Common::g_scm_branch); LOG_INFO(Loader, "Description {}", Common::g_scm_desc); LOG_INFO(Config, "General Logtype: {}", Config::getLogType()); LOG_INFO(Config, "General isNeo: {}", Config::isNeoMode()); LOG_INFO(Config, "GPU isNullGpu: {}", Config::nullGpu()); LOG_INFO(Config, "GPU shouldDumpShaders: {}", Config::dumpShaders()); LOG_INFO(Config, "GPU vblankDivider: {}", Config::vblankDiv()); LOG_INFO(Config, "Vulkan gpuId: {}", Config::getGpuId()); LOG_INFO(Config, "Vulkan vkValidation: {}", Config::vkValidationEnabled()); LOG_INFO(Config, "Vulkan vkValidationSync: {}", Config::vkValidationSyncEnabled()); LOG_INFO(Config, "Vulkan vkValidationGpu: {}", Config::vkValidationGpuEnabled()); LOG_INFO(Config, "Vulkan rdocEnable: {}", Config::isRdocEnabled()); LOG_INFO(Config, "Vulkan rdocMarkersEnable: {}", Config::vkMarkersEnabled()); LOG_INFO(Config, "Vulkan crashDiagnostics: {}", Config::vkCrashDiagnosticEnabled()); // Defer until after logging is initialized. memory = Core::Memory::Instance(); controller = Common::Singleton<Input::GameController>::Instance(); linker = Common::Singleton<Core::Linker>::Instance(); // Load renderdoc module. VideoCore::LoadRenderDoc(); // Start the timer (Play Time) #ifdef ENABLE_QT_GUI start_time = std::chrono::steady_clock::now(); const auto user_dir = Common::FS::GetUserPath(Common::FS::PathType::UserDir); QString filePath = QString::fromStdString((user_dir / "play_time.txt").string()); QFile file(filePath); if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) { LOG_INFO(Loader, "Error opening or creating play_time.txt"); } #endif } Emulator::~Emulator() { const auto config_dir = Common::FS::GetUserPath(Common::FS::PathType::UserDir); Config::save(config_dir / "config.toml"); } void Emulator::Run(const std::filesystem::path& file) { // Use the eboot from the separated updates folder if it's there std::filesystem::path game_patch_folder = file.parent_path().concat("-UPDATE"); bool use_game_patch = std::filesystem::exists(game_patch_folder / "sce_sys"); std::filesystem::path eboot_path = use_game_patch ? game_patch_folder / file.filename() : file; // Applications expect to be run from /app0 so mount the file's parent path as app0. auto* mnt = Common::Singleton<Core::FileSys::MntPoints>::Instance(); mnt->Mount(file.parent_path(), "/app0"); // Certain games may use /hostapp as well such as CUSA001100 mnt->Mount(file.parent_path(), "/hostapp"); auto& game_info = Common::ElfInfo::Instance(); // Loading param.sfo file if exists std::string id; std::string title; std::string app_version; u32 fw_version; std::filesystem::path sce_sys_folder = eboot_path.parent_path() / "sce_sys"; if (std::filesystem::is_directory(sce_sys_folder)) { for (const auto& entry : std::filesystem::directory_iterator(sce_sys_folder)) { if (entry.path().filename() == "param.sfo") { auto* param_sfo = Common::Singleton<PSF>::Instance(); const bool success = param_sfo->Open(sce_sys_folder / "param.sfo"); ASSERT_MSG(success, "Failed to open param.sfo"); const auto content_id = param_sfo->GetString("CONTENT_ID"); ASSERT_MSG(content_id.has_value(), "Failed to get CONTENT_ID"); id = std::string(*content_id, 7, 9); Libraries::NpTrophy::game_serial = id; const auto trophyDir = Common::FS::GetUserPath(Common::FS::PathType::MetaDataDir) / id / "TrophyFiles"; if (!std::filesystem::exists(trophyDir)) { TRP trp; if (!trp.Extract(eboot_path.parent_path(), id)) { LOG_ERROR(Loader, "Couldn't extract trophies"); } } #ifdef ENABLE_QT_GUI MemoryPatcher::g_game_serial = id; // Timer for 'Play Time' QTimer* timer = new QTimer(); QObject::connect(timer, &QTimer::timeout, [this, id]() { UpdatePlayTime(id); start_time = std::chrono::steady_clock::now(); }); timer->start(60000); // 60000 ms = 1 minute #endif title = param_sfo->GetString("TITLE").value_or("Unknown title"); LOG_INFO(Loader, "Game id: {} Title: {}", id, title); fw_version = param_sfo->GetInteger("SYSTEM_VER").value_or(0x4700000); app_version = param_sfo->GetString("APP_VER").value_or("Unknown version"); LOG_INFO(Loader, "Fw: {:#x} App Version: {}", fw_version, app_version); } else if (entry.path().filename() == "playgo-chunk.dat") { auto* playgo = Common::Singleton<PlaygoFile>::Instance(); auto filepath = sce_sys_folder / "playgo-chunk.dat"; if (!playgo->Open(filepath)) { LOG_ERROR(Loader, "PlayGo: unable to open file"); } } else if (entry.path().filename() == "pic0.png" || entry.path().filename() == "pic1.png") { auto* splash = Common::Singleton<Splash>::Instance(); if (splash->IsLoaded()) { continue; } if (!splash->Open(entry.path())) { LOG_ERROR(Loader, "Game splash: unable to open file"); } } } } game_info.initialized = true; game_info.game_serial = id; game_info.title = title; game_info.app_ver = app_version; game_info.firmware_ver = fw_version & 0xFFF00000; game_info.raw_firmware_ver = fw_version; std::string game_title = fmt::format("{} - {} <{}>", id, title, app_version); std::string window_title = ""; if (Common::isRelease) { window_title = fmt::format("shadPS4 v{} | {}", Common::VERSION, game_title); } else { window_title = fmt::format("shadPS4 v{} {} {} | {}", Common::VERSION, Common::g_scm_branch, Common::g_scm_desc, game_title); } window = std::make_unique<Frontend::WindowSDL>( Config::getScreenWidth(), Config::getScreenHeight(), controller, window_title); g_window = window.get(); const auto& mount_data_dir = Common::FS::GetUserPath(Common::FS::PathType::GameDataDir) / id; if (!std::filesystem::exists(mount_data_dir)) { std::filesystem::create_directory(mount_data_dir); } mnt->Mount(mount_data_dir, "/data"); // should just exist, manually create with game serial const auto& mount_temp_dir = Common::FS::GetUserPath(Common::FS::PathType::TempDataDir) / id; if (!std::filesystem::exists(mount_temp_dir)) { std::filesystem::create_directory(mount_temp_dir); } mnt->Mount(mount_temp_dir, "/temp0"); // called in app_content ==> stat/mkdir mnt->Mount(mount_temp_dir, "/temp"); const auto& mount_download_dir = Common::FS::GetUserPath(Common::FS::PathType::DownloadDir) / id; if (!std::filesystem::exists(mount_download_dir)) { std::filesystem::create_directory(mount_download_dir); } mnt->Mount(mount_download_dir, "/download0"); const auto& mount_captures_dir = Common::FS::GetUserPath(Common::FS::PathType::CapturesDir); if (!std::filesystem::exists(mount_captures_dir)) { std::filesystem::create_directory(mount_captures_dir); } VideoCore::SetOutputDir(mount_captures_dir, id); // Initialize kernel and library facilities. Libraries::Kernel::init_pthreads(); Libraries::InitHLELibs(&linker->GetHLESymbols()); // Load the module with the linker linker->LoadModule(eboot_path); // check if we have system modules to load LoadSystemModules(eboot_path, game_info.game_serial); // Load all prx from game's sce_module folder std::filesystem::path sce_module_folder = file.parent_path() / "sce_module"; if (std::filesystem::is_directory(sce_module_folder)) { for (const auto& entry : std::filesystem::directory_iterator(sce_module_folder)) { std::filesystem::path module_path = entry.path(); std::filesystem::path update_module_path = eboot_path.parent_path() / "sce_module" / entry.path().filename(); if (std::filesystem::exists(update_module_path) && use_game_patch) { module_path = update_module_path; } LOG_INFO(Loader, "Loading {}", fmt::UTF(module_path.u8string())); linker->LoadModule(module_path); } } #ifdef ENABLE_DISCORD_RPC // Discord RPC if (Config::getEnableDiscordRPC()) { auto* rpc = Common::Singleton<DiscordRPCHandler::RPC>::Instance(); if (rpc->getRPCEnabled() == false) { rpc->init(); } rpc->setStatusPlaying(game_info.title, id); } #endif // start execution std::jthread mainthread = std::jthread([this](std::stop_token stop_token) { linker->Execute(); }); window->initTimers(); while (window->isOpen()) { window->waitEvent(); } #ifdef ENABLE_QT_GUI UpdatePlayTime(id); #endif std::exit(0); } void Emulator::LoadSystemModules(const std::filesystem::path& file, std::string game_serial) { constexpr std::array<SysModules, 11> ModulesToLoad{ {{"libSceNgs2.sprx", &Libraries::Ngs2::RegisterlibSceNgs2}, {"libSceFiber.sprx", &Libraries::Fiber::RegisterlibSceFiber}, {"libSceUlt.sprx", nullptr}, {"libSceJson.sprx", nullptr}, {"libSceJson2.sprx", nullptr}, {"libSceLibcInternal.sprx", &Libraries::LibcInternal::RegisterlibSceLibcInternal}, {"libSceDiscMap.sprx", &Libraries::DiscMap::RegisterlibSceDiscMap}, {"libSceRtc.sprx", &Libraries::Rtc::RegisterlibSceRtc}, {"libSceJpegEnc.sprx", nullptr}, {"libSceRazorCpu.sprx", nullptr}, {"libSceCesCs.sprx", nullptr}}}; std::vector<std::filesystem::path> found_modules; const auto& sys_module_path = Common::FS::GetUserPath(Common::FS::PathType::SysModuleDir); for (const auto& entry : std::filesystem::directory_iterator(sys_module_path)) { found_modules.push_back(entry.path()); } for (const auto& [module_name, init_func] : ModulesToLoad) { const auto it = std::ranges::find_if( found_modules, [&](const auto& path) { return path.filename() == module_name; }); if (it != found_modules.end()) { LOG_INFO(Loader, "Loading {}", it->string()); linker->LoadModule(*it); continue; } if (init_func) { LOG_INFO(Loader, "Can't Load {} switching to HLE", module_name); init_func(&linker->GetHLESymbols()); } else { LOG_INFO(Loader, "No HLE available for {} module", module_name); } } if (std::filesystem::exists(sys_module_path / game_serial)) { for (const auto& entry : std::filesystem::directory_iterator(sys_module_path / game_serial)) { LOG_INFO(Loader, "Loading {} from game serial file {}", entry.path().string(), game_serial); linker->LoadModule(entry.path()); } } } #ifdef ENABLE_QT_GUI void Emulator::UpdatePlayTime(const std::string& serial) { const auto user_dir = Common::FS::GetUserPath(Common::FS::PathType::UserDir); QString filePath = QString::fromStdString((user_dir / "play_time.txt").string()); QFile file(filePath); if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) { LOG_INFO(Loader, "Error opening play_time.txt"); return; } auto end_time = std::chrono::steady_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time); int totalSeconds = duration.count(); QTextStream in(&file); QStringList lines; QString content; while (!in.atEnd()) { content += in.readLine() + "\n"; } file.close(); QStringList existingLines = content.split('\n', Qt::SkipEmptyParts); int accumulatedSeconds = 0; bool found = false; for (const QString& line : existingLines) { QStringList parts = line.split(' '); if (parts.size() == 2 && parts[0] == QString::fromStdString(serial)) { QStringList timeParts = parts[1].split(':'); if (timeParts.size() == 3) { int hours = timeParts[0].toInt(); int minutes = timeParts[1].toInt(); int seconds = timeParts[2].toInt(); accumulatedSeconds = hours * 3600 + minutes * 60 + seconds; found = true; break; } } } accumulatedSeconds += totalSeconds; int hours = accumulatedSeconds / 3600; int minutes = (accumulatedSeconds % 3600) / 60; int seconds = accumulatedSeconds % 60; QString playTimeSaved = QString::number(hours) + ":" + QString::number(minutes).rightJustified(2, '0') + ":" + QString::number(seconds).rightJustified(2, '0'); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream out(&file); bool lineUpdated = false; for (const QString& line : existingLines) { if (line.startsWith(QString::fromStdString(serial))) { out << QString::fromStdString(serial) + " " + playTimeSaved + "\n"; lineUpdated = true; } else { out << line << "\n"; } } if (!lineUpdated) { out << QString::fromStdString(serial) + " " + playTimeSaved + "\n"; } } LOG_INFO(Loader, "Playing time for {}: {}", serial, playTimeSaved.toStdString()); } #endif } // namespace Core
15,917
C++
.cpp
344
38.363372
100
0.623366
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,536
sdl_window.cpp
shadps4-emu_shadPS4/src/sdl_window.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <SDL3/SDL_events.h> #include <SDL3/SDL_init.h> #include <SDL3/SDL_properties.h> #include <SDL3/SDL_timer.h> #include <SDL3/SDL_video.h> #include "common/assert.h" #include "common/config.h" #include "common/version.h" #include "core/libraries/pad/pad.h" #include "imgui/renderer/imgui_core.h" #include "input/controller.h" #include "sdl_window.h" #include "video_core/renderdoc.h" #ifdef __APPLE__ #include <SDL3/SDL_metal.h> #endif namespace Frontend { static Uint32 SDLCALL PollController(void* userdata, SDL_TimerID timer_id, Uint32 interval) { auto* controller = reinterpret_cast<Input::GameController*>(userdata); return controller->Poll(); } WindowSDL::WindowSDL(s32 width_, s32 height_, Input::GameController* controller_, std::string_view window_title) : width{width_}, height{height_}, controller{controller_} { if (!SDL_Init(SDL_INIT_VIDEO)) { UNREACHABLE_MSG("Failed to initialize SDL video subsystem: {}", SDL_GetError()); } SDL_InitSubSystem(SDL_INIT_AUDIO); SDL_PropertiesID props = SDL_CreateProperties(); SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, std::string(window_title).c_str()); SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, SDL_WINDOWPOS_CENTERED); SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, SDL_WINDOWPOS_CENTERED); SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, width); SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, height); SDL_SetNumberProperty(props, "flags", SDL_WINDOW_VULKAN); SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, true); window = SDL_CreateWindowWithProperties(props); SDL_DestroyProperties(props); if (window == nullptr) { UNREACHABLE_MSG("Failed to create window handle: {}", SDL_GetError()); } SDL_SetWindowFullscreen(window, Config::isFullscreenMode()); SDL_InitSubSystem(SDL_INIT_GAMEPAD); controller->TryOpenSDLController(); #if defined(SDL_PLATFORM_WIN32) window_info.type = WindowSystemType::Windows; window_info.render_surface = SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL); #elif defined(SDL_PLATFORM_LINUX) if (SDL_strcmp(SDL_GetCurrentVideoDriver(), "x11") == 0) { window_info.type = WindowSystemType::X11; window_info.display_connection = SDL_GetPointerProperty( SDL_GetWindowProperties(window), SDL_PROP_WINDOW_X11_DISPLAY_POINTER, NULL); window_info.render_surface = (void*)SDL_GetNumberProperty( SDL_GetWindowProperties(window), SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0); } else if (SDL_strcmp(SDL_GetCurrentVideoDriver(), "wayland") == 0) { window_info.type = WindowSystemType::Wayland; window_info.display_connection = SDL_GetPointerProperty( SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WAYLAND_DISPLAY_POINTER, NULL); window_info.render_surface = SDL_GetPointerProperty( SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WAYLAND_SURFACE_POINTER, NULL); } #elif defined(SDL_PLATFORM_MACOS) window_info.type = WindowSystemType::Metal; window_info.render_surface = SDL_Metal_GetLayer(SDL_Metal_CreateView(window)); #endif } WindowSDL::~WindowSDL() = default; void WindowSDL::waitEvent() { // Called on main thread SDL_Event event; if (!SDL_WaitEvent(&event)) { return; } if (ImGui::Core::ProcessEvent(&event)) { return; } switch (event.type) { case SDL_EVENT_WINDOW_RESIZED: case SDL_EVENT_WINDOW_MAXIMIZED: case SDL_EVENT_WINDOW_RESTORED: onResize(); break; case SDL_EVENT_WINDOW_MINIMIZED: case SDL_EVENT_WINDOW_EXPOSED: is_shown = event.type == SDL_EVENT_WINDOW_EXPOSED; onResize(); break; case SDL_EVENT_KEY_DOWN: case SDL_EVENT_KEY_UP: onKeyPress(&event); break; case SDL_EVENT_GAMEPAD_BUTTON_DOWN: case SDL_EVENT_GAMEPAD_BUTTON_UP: case SDL_EVENT_GAMEPAD_AXIS_MOTION: case SDL_EVENT_GAMEPAD_ADDED: case SDL_EVENT_GAMEPAD_REMOVED: case SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN: case SDL_EVENT_GAMEPAD_TOUCHPAD_UP: case SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION: onGamepadEvent(&event); break; case SDL_EVENT_QUIT: is_open = false; break; default: break; } } void WindowSDL::initTimers() { SDL_AddTimer(100, &PollController, controller); } void WindowSDL::onResize() { SDL_GetWindowSizeInPixels(window, &width, &height); ImGui::Core::OnResize(); } void WindowSDL::onKeyPress(const SDL_Event* event) { using Libraries::Pad::OrbisPadButtonDataOffset; #ifdef __APPLE__ // Use keys that are more friendly for keyboards without a keypad. // Once there are key binding options this won't be necessary. constexpr SDL_Keycode CrossKey = SDLK_N; constexpr SDL_Keycode CircleKey = SDLK_B; constexpr SDL_Keycode SquareKey = SDLK_V; constexpr SDL_Keycode TriangleKey = SDLK_C; #else constexpr SDL_Keycode CrossKey = SDLK_KP_2; constexpr SDL_Keycode CircleKey = SDLK_KP_6; constexpr SDL_Keycode SquareKey = SDLK_KP_4; constexpr SDL_Keycode TriangleKey = SDLK_KP_8; #endif u32 button = 0; Input::Axis axis = Input::Axis::AxisMax; int axisvalue = 0; int ax = 0; std::string backButtonBehavior = Config::getBackButtonBehavior(); switch (event->key.key) { case SDLK_UP: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_UP; break; case SDLK_DOWN: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_DOWN; break; case SDLK_LEFT: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_LEFT; break; case SDLK_RIGHT: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_RIGHT; break; case TriangleKey: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_TRIANGLE; break; case CircleKey: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_CIRCLE; break; case CrossKey: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_CROSS; break; case SquareKey: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_SQUARE; break; case SDLK_RETURN: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_OPTIONS; break; case SDLK_A: axis = Input::Axis::LeftX; if (event->type == SDL_EVENT_KEY_DOWN) { axisvalue += -127; } else { axisvalue = 0; } ax = Input::GetAxis(-0x80, 0x80, axisvalue); break; case SDLK_D: axis = Input::Axis::LeftX; if (event->type == SDL_EVENT_KEY_DOWN) { axisvalue += 127; } else { axisvalue = 0; } ax = Input::GetAxis(-0x80, 0x80, axisvalue); break; case SDLK_W: axis = Input::Axis::LeftY; if (event->type == SDL_EVENT_KEY_DOWN) { axisvalue += -127; } else { axisvalue = 0; } ax = Input::GetAxis(-0x80, 0x80, axisvalue); break; case SDLK_S: axis = Input::Axis::LeftY; if (event->type == SDL_EVENT_KEY_DOWN) { axisvalue += 127; } else { axisvalue = 0; } ax = Input::GetAxis(-0x80, 0x80, axisvalue); break; case SDLK_J: axis = Input::Axis::RightX; if (event->type == SDL_EVENT_KEY_DOWN) { axisvalue += -127; } else { axisvalue = 0; } ax = Input::GetAxis(-0x80, 0x80, axisvalue); break; case SDLK_L: axis = Input::Axis::RightX; if (event->type == SDL_EVENT_KEY_DOWN) { axisvalue += 127; } else { axisvalue = 0; } ax = Input::GetAxis(-0x80, 0x80, axisvalue); break; case SDLK_I: axis = Input::Axis::RightY; if (event->type == SDL_EVENT_KEY_DOWN) { axisvalue += -127; } else { axisvalue = 0; } ax = Input::GetAxis(-0x80, 0x80, axisvalue); break; case SDLK_K: axis = Input::Axis::RightY; if (event->type == SDL_EVENT_KEY_DOWN) { axisvalue += 127; } else { axisvalue = 0; } ax = Input::GetAxis(-0x80, 0x80, axisvalue); break; case SDLK_X: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_L3; break; case SDLK_M: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_R3; break; case SDLK_Q: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_L1; break; case SDLK_U: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_R1; break; case SDLK_E: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_L2; axis = Input::Axis::TriggerLeft; if (event->type == SDL_EVENT_KEY_DOWN) { axisvalue += 255; } else { axisvalue = 0; } ax = Input::GetAxis(0, 0x80, axisvalue); break; case SDLK_O: button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_R2; axis = Input::Axis::TriggerRight; if (event->type == SDL_EVENT_KEY_DOWN) { axisvalue += 255; } else { axisvalue = 0; } ax = Input::GetAxis(0, 0x80, axisvalue); break; case SDLK_SPACE: if (backButtonBehavior != "none") { float x = backButtonBehavior == "left" ? 0.25f : (backButtonBehavior == "right" ? 0.75f : 0.5f); // trigger a touchpad event so that the touchpad emulation for back button works controller->SetTouchpadState(0, true, x, 0.5f); button = OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_TOUCH_PAD; } else { button = 0; } break; case SDLK_F11: if (event->type == SDL_EVENT_KEY_DOWN) { { SDL_WindowFlags flag = SDL_GetWindowFlags(window); bool is_fullscreen = flag & SDL_WINDOW_FULLSCREEN; SDL_SetWindowFullscreen(window, !is_fullscreen); } } break; case SDLK_F12: if (event->type == SDL_EVENT_KEY_DOWN) { // Trigger rdoc capture VideoCore::TriggerCapture(); } break; default: break; } if (button != 0) { controller->CheckButton(0, button, event->type == SDL_EVENT_KEY_DOWN); } if (axis != Input::Axis::AxisMax) { controller->Axis(0, axis, ax); } } void WindowSDL::onGamepadEvent(const SDL_Event* event) { using Libraries::Pad::OrbisPadButtonDataOffset; u32 button = 0; Input::Axis axis = Input::Axis::AxisMax; switch (event->type) { case SDL_EVENT_GAMEPAD_ADDED: case SDL_EVENT_GAMEPAD_REMOVED: controller->TryOpenSDLController(); break; case SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN: case SDL_EVENT_GAMEPAD_TOUCHPAD_UP: case SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION: controller->SetTouchpadState(event->gtouchpad.finger, event->type != SDL_EVENT_GAMEPAD_TOUCHPAD_UP, event->gtouchpad.x, event->gtouchpad.y); break; case SDL_EVENT_GAMEPAD_BUTTON_DOWN: case SDL_EVENT_GAMEPAD_BUTTON_UP: button = sdlGamepadToOrbisButton(event->gbutton.button); if (button != 0) { if (event->gbutton.button == SDL_GAMEPAD_BUTTON_BACK) { std::string backButtonBehavior = Config::getBackButtonBehavior(); if (backButtonBehavior != "none") { float x = backButtonBehavior == "left" ? 0.25f : (backButtonBehavior == "right" ? 0.75f : 0.5f); // trigger a touchpad event so that the touchpad emulation for back button works controller->SetTouchpadState(0, true, x, 0.5f); controller->CheckButton(0, button, event->type == SDL_EVENT_GAMEPAD_BUTTON_DOWN); } } else { controller->CheckButton(0, button, event->type == SDL_EVENT_GAMEPAD_BUTTON_DOWN); } } break; case SDL_EVENT_GAMEPAD_AXIS_MOTION: axis = event->gaxis.axis == SDL_GAMEPAD_AXIS_LEFTX ? Input::Axis::LeftX : event->gaxis.axis == SDL_GAMEPAD_AXIS_LEFTY ? Input::Axis::LeftY : event->gaxis.axis == SDL_GAMEPAD_AXIS_RIGHTX ? Input::Axis::RightX : event->gaxis.axis == SDL_GAMEPAD_AXIS_RIGHTY ? Input::Axis::RightY : event->gaxis.axis == SDL_GAMEPAD_AXIS_LEFT_TRIGGER ? Input::Axis::TriggerLeft : event->gaxis.axis == SDL_GAMEPAD_AXIS_RIGHT_TRIGGER ? Input::Axis::TriggerRight : Input::Axis::AxisMax; if (axis != Input::Axis::AxisMax) { if (event->gaxis.axis == SDL_GAMEPAD_AXIS_LEFT_TRIGGER || event->gaxis.axis == SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) { controller->Axis(0, axis, Input::GetAxis(0, 0x8000, event->gaxis.value)); } else { controller->Axis(0, axis, Input::GetAxis(-0x8000, 0x8000, event->gaxis.value)); } } break; } } int WindowSDL::sdlGamepadToOrbisButton(u8 button) { using Libraries::Pad::OrbisPadButtonDataOffset; switch (button) { case SDL_GAMEPAD_BUTTON_DPAD_DOWN: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_DOWN; case SDL_GAMEPAD_BUTTON_DPAD_UP: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_UP; case SDL_GAMEPAD_BUTTON_DPAD_LEFT: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_LEFT; case SDL_GAMEPAD_BUTTON_DPAD_RIGHT: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_RIGHT; case SDL_GAMEPAD_BUTTON_SOUTH: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_CROSS; case SDL_GAMEPAD_BUTTON_NORTH: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_TRIANGLE; case SDL_GAMEPAD_BUTTON_WEST: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_SQUARE; case SDL_GAMEPAD_BUTTON_EAST: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_CIRCLE; case SDL_GAMEPAD_BUTTON_START: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_OPTIONS; case SDL_GAMEPAD_BUTTON_TOUCHPAD: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_TOUCH_PAD; case SDL_GAMEPAD_BUTTON_BACK: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_TOUCH_PAD; case SDL_GAMEPAD_BUTTON_LEFT_SHOULDER: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_L1; case SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_R1; case SDL_GAMEPAD_BUTTON_LEFT_STICK: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_L3; case SDL_GAMEPAD_BUTTON_RIGHT_STICK: return OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_R3; default: return 0; } } } // namespace Frontend
15,537
C++
.cpp
400
30.41
100
0.625066
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,537
controller.cpp
shadps4-emu_shadPS4/src/input/controller.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "controller.h" #include "common/assert.h" #include "core/libraries/kernel/time_management.h" #include "core/libraries/pad/pad.h" #include <SDL3/SDL.h> namespace Input { GameController::GameController() { m_states_num = 0; m_last_state = State(); } void GameController::ReadState(State* state, bool* isConnected, int* connectedCount) { std::scoped_lock lock{m_mutex}; *isConnected = m_connected; *connectedCount = m_connected_count; *state = GetLastState(); } int GameController::ReadStates(State* states, int states_num, bool* isConnected, int* connectedCount) { std::scoped_lock lock{m_mutex}; *isConnected = m_connected; *connectedCount = m_connected_count; int ret_num = 0; if (m_connected) { if (m_states_num == 0) { ret_num = 1; states[0] = m_last_state; } else { for (uint32_t i = 0; i < m_states_num; i++) { if (ret_num >= states_num) { break; } auto index = (m_first_state + i) % MAX_STATES; if (!m_private[index].obtained) { m_private[index].obtained = true; states[ret_num++] = m_states[index]; } } } } return ret_num; } State GameController::GetLastState() const { if (m_states_num == 0) { return m_last_state; } auto last = (m_first_state + m_states_num - 1) % MAX_STATES; return m_states[last]; } void GameController::AddState(const State& state) { if (m_states_num >= MAX_STATES) { m_states_num = MAX_STATES - 1; m_first_state = (m_first_state + 1) % MAX_STATES; } auto index = (m_first_state + m_states_num) % MAX_STATES; m_states[index] = state; m_last_state = state; m_private[index].obtained = false; m_states_num++; } void GameController::CheckButton(int id, u32 button, bool isPressed) { std::scoped_lock lock{m_mutex}; auto state = GetLastState(); state.time = Libraries::Kernel::sceKernelGetProcessTime(); if (isPressed) { state.buttonsState |= button; } else { state.buttonsState &= ~button; } AddState(state); } void GameController::Axis(int id, Input::Axis axis, int value) { std::scoped_lock lock{m_mutex}; auto state = GetLastState(); state.time = Libraries::Kernel::sceKernelGetProcessTime(); int axis_id = static_cast<int>(axis); state.axes[axis_id] = value; if (axis == Input::Axis::TriggerLeft) { if (value > 0) { state.buttonsState |= Libraries::Pad::OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_L2; } else { state.buttonsState &= ~Libraries::Pad::OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_L2; } } if (axis == Input::Axis::TriggerRight) { if (value > 0) { state.buttonsState |= Libraries::Pad::OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_R2; } else { state.buttonsState &= ~Libraries::Pad::OrbisPadButtonDataOffset::ORBIS_PAD_BUTTON_R2; } } AddState(state); } void GameController::SetLightBarRGB(u8 r, u8 g, u8 b) { if (m_sdl_gamepad != nullptr) { SDL_SetGamepadLED(m_sdl_gamepad, r, g, b); } } bool GameController::SetVibration(u8 smallMotor, u8 largeMotor) { if (m_sdl_gamepad != nullptr) { return SDL_RumbleGamepad(m_sdl_gamepad, (smallMotor / 255.0f) * 0xFFFF, (largeMotor / 255.0f) * 0xFFFF, -1); } return true; } void GameController::SetTouchpadState(int touchIndex, bool touchDown, float x, float y) { if (touchIndex < 2) { std::scoped_lock lock{m_mutex}; auto state = GetLastState(); state.time = Libraries::Kernel::sceKernelGetProcessTime(); state.touchpad[touchIndex].state = touchDown; state.touchpad[touchIndex].x = static_cast<u16>(x * 1920); state.touchpad[touchIndex].y = static_cast<u16>(y * 941); AddState(state); } } void GameController::TryOpenSDLController() { if (m_sdl_gamepad == nullptr || !SDL_GamepadConnected(m_sdl_gamepad)) { int gamepad_count; SDL_JoystickID* gamepads = SDL_GetGamepads(&gamepad_count); m_sdl_gamepad = gamepad_count > 0 ? SDL_OpenGamepad(gamepads[0]) : nullptr; SDL_free(gamepads); SetLightBarRGB(0, 0, 255); } } u32 GameController::Poll() { if (m_connected) { auto time = Libraries::Kernel::sceKernelGetProcessTime(); if (m_states_num == 0) { auto diff = (time - m_last_state.time) / 1000; if (diff >= 100) { AddState(GetLastState()); } } else { auto index = (m_first_state - 1 + m_states_num) % MAX_STATES; auto diff = (time - m_states[index].time) / 1000; if (m_private[index].obtained && diff >= 100) { AddState(GetLastState()); } } } return 100; } } // namespace Input
5,192
C++
.cpp
145
28.455172
97
0.604192
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,538
virtual_memory.cpp
shadps4-emu_shadPS4/src/core/virtual_memory.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/assert.h" #include "common/error.h" #include "common/logging/log.h" #include "core/virtual_memory.h" #ifdef _WIN64 #include <windows.h> #else #include <sys/mman.h> #endif #if !defined(_WIN64) enum PosixPageProtection { PAGE_NOACCESS = 0, PAGE_READONLY = PROT_READ, PAGE_READWRITE = PROT_READ | PROT_WRITE, PAGE_EXECUTE = PROT_EXEC, PAGE_EXECUTE_READ = PROT_EXEC | PROT_READ, PAGE_EXECUTE_READWRITE = PROT_EXEC | PROT_READ | PROT_WRITE }; #endif namespace VirtualMemory { static u32 convertMemoryMode(MemoryMode mode) { switch (mode) { case MemoryMode::Read: return PAGE_READONLY; case MemoryMode::Write: case MemoryMode::ReadWrite: return PAGE_READWRITE; case MemoryMode::Execute: return PAGE_EXECUTE; case MemoryMode::ExecuteRead: return PAGE_EXECUTE_READ; case MemoryMode::ExecuteWrite: case MemoryMode::ExecuteReadWrite: return PAGE_EXECUTE_READWRITE; case MemoryMode::NoAccess: return PAGE_NOACCESS; default: return PAGE_NOACCESS; } } static MemoryMode convertMemoryMode(u32 mode) { switch (mode) { case PAGE_NOACCESS: return MemoryMode::NoAccess; case PAGE_READONLY: return MemoryMode::Read; case PAGE_READWRITE: return MemoryMode::ReadWrite; case PAGE_EXECUTE: return MemoryMode::Execute; case PAGE_EXECUTE_READ: return MemoryMode::ExecuteRead; case PAGE_EXECUTE_READWRITE: return MemoryMode::ExecuteReadWrite; default: return MemoryMode::NoAccess; } } u64 memory_alloc(u64 address, u64 size, MemoryMode mode) { #ifdef _WIN64 auto ptr = reinterpret_cast<uintptr_t>(VirtualAlloc( reinterpret_cast<LPVOID>(static_cast<uintptr_t>(address)), size, static_cast<DWORD>(MEM_COMMIT) | static_cast<DWORD>(MEM_RESERVE), convertMemoryMode(mode))); if (ptr == 0) { auto err = static_cast<u32>(GetLastError()); LOG_ERROR(Common_Memory, "VirtualAlloc() failed: 0x{:X}", err); } #else auto ptr = reinterpret_cast<uintptr_t>( mmap(reinterpret_cast<void*>(static_cast<uintptr_t>(address)), size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0)); if (ptr == reinterpret_cast<uintptr_t> MAP_FAILED) { LOG_ERROR(Common_Memory, "mmap() failed: {}", std::strerror(errno)); } #endif return ptr; } bool memory_protect(u64 address, u64 size, MemoryMode mode, MemoryMode* old_mode) { #ifdef _WIN64 DWORD old_protect = 0; if (VirtualProtect(reinterpret_cast<LPVOID>(static_cast<uintptr_t>(address)), size, convertMemoryMode(mode), &old_protect) == 0) { auto err = static_cast<u32>(GetLastError()); LOG_ERROR(Common_Memory, "VirtualProtect() failed: 0x{:X}", err); return false; } if (old_mode != nullptr) { *old_mode = convertMemoryMode(old_protect); } return true; #else int ret = mprotect(reinterpret_cast<void*>(address), size, convertMemoryMode(mode)); if (ret != 0) { const auto error = Common::GetLastErrorMsg(); ASSERT(false); } return true; #endif } bool memory_flush(u64 address, u64 size) { #ifdef _WIN64 if (::FlushInstructionCache(GetCurrentProcess(), reinterpret_cast<LPVOID>(static_cast<uintptr_t>(address)), size) == 0) { auto err = static_cast<u32>(GetLastError()); LOG_ERROR(Common_Memory, "FlushInstructionCache() failed: 0x{:X}", err); return false; } return true; #else // linux probably doesn't have something similar return true; #endif } bool memory_patch(u64 vaddr, u64 value) { MemoryMode old_mode{}; // memory_protect(vaddr, 8, MemoryMode::ReadWrite, &old_mode); auto* ptr = reinterpret_cast<uint64_t*>(vaddr); bool ret = (*ptr != value); *ptr = value; // memory_protect(vaddr, 8, old_mode, nullptr); // if mode is executable flush it so insure that cpu finds it if (containsExecuteMode(old_mode)) { memory_flush(vaddr, 8); } return ret; } static u64 AlignUp(u64 pos, u64 align) { return (align != 0 ? (pos + (align - 1)) & ~(align - 1) : pos); } u64 memory_alloc_aligned(u64 address, u64 size, MemoryMode mode, u64 alignment) { #ifdef _WIN64 // try allocate aligned address inside user area MEM_ADDRESS_REQUIREMENTS req{}; MEM_EXTENDED_PARAMETER param{}; req.LowestStartingAddress = (address == 0 ? reinterpret_cast<PVOID>(USER_MIN) : reinterpret_cast<PVOID>(AlignUp(address, alignment))); req.HighestEndingAddress = reinterpret_cast<PVOID>(USER_MAX); req.Alignment = alignment; param.Type = MemExtendedParameterAddressRequirements; param.Pointer = &req; auto ptr = reinterpret_cast<uintptr_t>( VirtualAlloc2(GetCurrentProcess(), nullptr, size, static_cast<DWORD>(MEM_COMMIT) | static_cast<DWORD>(MEM_RESERVE), convertMemoryMode(mode), &param, 1)); if (ptr == 0) { auto err = static_cast<u32>(GetLastError()); LOG_ERROR(Common_Memory, "VirtualAlloc2() failed: 0x{:X}", err); } return ptr; #else void* hint_address = address == 0 ? reinterpret_cast<void*>(USER_MIN) : reinterpret_cast<void*>(AlignUp(address, alignment)); void* ptr = mmap(hint_address, size, convertMemoryMode(mode), MAP_ANON | MAP_PRIVATE, -1, 0); ASSERT(ptr != MAP_FAILED); return reinterpret_cast<u64>(ptr); #endif } } // namespace VirtualMemory
5,765
C++
.cpp
161
29.89441
100
0.659266
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,539
cpu_patches.cpp
shadps4-emu_shadPS4/src/core/cpu_patches.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <map> #include <memory> #include <mutex> #include <set> #include <Zydis/Zydis.h> #include <xbyak/xbyak.h> #include <xbyak/xbyak_util.h> #include "common/alignment.h" #include "common/arch.h" #include "common/assert.h" #include "common/decoder.h" #include "common/signal_context.h" #include "common/types.h" #include "core/signals.h" #include "core/tls.h" #include "cpu_patches.h" #ifdef _WIN32 #include <windows.h> #else #include <pthread.h> #ifdef __APPLE__ #include <half.hpp> #include <sys/sysctl.h> #endif #endif using namespace Xbyak::util; #define MAYBE_AVX(OPCODE, ...) \ [&] { \ Cpu cpu; \ if (cpu.has(Cpu::tAVX)) { \ c.v##OPCODE(__VA_ARGS__); \ } else { \ c.OPCODE(__VA_ARGS__); \ } \ }() namespace Core { static Xbyak::Reg ZydisToXbyakRegister(const ZydisRegister reg) { if (reg >= ZYDIS_REGISTER_EAX && reg <= ZYDIS_REGISTER_R15D) { return Xbyak::Reg32(reg - ZYDIS_REGISTER_EAX + Xbyak::Operand::EAX); } if (reg >= ZYDIS_REGISTER_RAX && reg <= ZYDIS_REGISTER_R15) { return Xbyak::Reg64(reg - ZYDIS_REGISTER_RAX + Xbyak::Operand::RAX); } if (reg >= ZYDIS_REGISTER_XMM0 && reg <= ZYDIS_REGISTER_XMM31) { return Xbyak::Xmm(reg - ZYDIS_REGISTER_XMM0 + xmm0.getIdx()); } if (reg >= ZYDIS_REGISTER_YMM0 && reg <= ZYDIS_REGISTER_YMM31) { return Xbyak::Ymm(reg - ZYDIS_REGISTER_YMM0 + ymm0.getIdx()); } UNREACHABLE_MSG("Unsupported register: {}", static_cast<u32>(reg)); } static Xbyak::Reg ZydisToXbyakRegisterOperand(const ZydisDecodedOperand& operand) { ASSERT_MSG(operand.type == ZYDIS_OPERAND_TYPE_REGISTER, "Expected register operand, got type: {}", static_cast<u32>(operand.type)); return ZydisToXbyakRegister(operand.reg.value); } static Xbyak::Address ZydisToXbyakMemoryOperand(const ZydisDecodedOperand& operand) { ASSERT_MSG(operand.type == ZYDIS_OPERAND_TYPE_MEMORY, "Expected memory operand, got type: {}", static_cast<u32>(operand.type)); if (operand.mem.base == ZYDIS_REGISTER_RIP) { return ptr[rip + operand.mem.disp.value]; } Xbyak::RegExp expression{}; if (operand.mem.base != ZYDIS_REGISTER_NONE) { expression = expression + ZydisToXbyakRegister(operand.mem.base); } if (operand.mem.index != ZYDIS_REGISTER_NONE) { if (operand.mem.scale != 0) { expression = expression + ZydisToXbyakRegister(operand.mem.index) * operand.mem.scale; } else { expression = expression + ZydisToXbyakRegister(operand.mem.index); } } if (operand.mem.disp.size != 0 && operand.mem.disp.value != 0) { expression = expression + operand.mem.disp.value; } return ptr[expression]; } static u64 ZydisToXbyakImmediateOperand(const ZydisDecodedOperand& operand) { ASSERT_MSG(operand.type == ZYDIS_OPERAND_TYPE_IMMEDIATE, "Expected immediate operand, got type: {}", static_cast<u32>(operand.type)); return operand.imm.value.u; } static std::unique_ptr<Xbyak::Operand> ZydisToXbyakOperand(const ZydisDecodedOperand& operand) { switch (operand.type) { case ZYDIS_OPERAND_TYPE_REGISTER: { return std::make_unique<Xbyak::Reg>(ZydisToXbyakRegisterOperand(operand)); } case ZYDIS_OPERAND_TYPE_MEMORY: { return std::make_unique<Xbyak::Address>(ZydisToXbyakMemoryOperand(operand)); } default: UNREACHABLE_MSG("Unsupported operand type: {}", static_cast<u32>(operand.type)); } } static bool OperandUsesRegister(const Xbyak::Operand* operand, int index) { if (operand->isREG()) { return operand->getIdx() == index; } if (operand->isMEM()) { const Xbyak::RegExp& reg_exp = operand->getAddress().getRegExp(); return reg_exp.getBase().getIdx() == index || reg_exp.getIndex().getIdx() == index; } UNREACHABLE_MSG("Unsupported operand kind: {}", static_cast<u32>(operand->getKind())); } static bool IsRegisterAllocated( const std::initializer_list<const Xbyak::Operand*>& allocated_registers, const int index) { return std::ranges::find_if(allocated_registers.begin(), allocated_registers.end(), [index](const Xbyak::Operand* operand) { return OperandUsesRegister(operand, index); }) != allocated_registers.end(); } static Xbyak::Reg AllocateScratchRegister( const std::initializer_list<const Xbyak::Operand*> allocated_registers, const u32 bits) { for (int index = Xbyak::Operand::R8; index <= Xbyak::Operand::R15; index++) { if (!IsRegisterAllocated(allocated_registers, index)) { return Xbyak::Reg32e(index, static_cast<int>(bits)); } } UNREACHABLE_MSG("Out of scratch registers!"); } #ifdef __APPLE__ static pthread_key_t stack_pointer_slot; static pthread_key_t patch_stack_slot; static std::once_flag patch_context_slots_init_flag; static constexpr u32 patch_stack_size = 0x1000; static_assert(sizeof(void*) == sizeof(u64), "Cannot fit a register inside a thread local storage slot."); static void FreePatchStack(void* patch_stack) { // Subtract back to the bottom of the stack for free. std::free(static_cast<u8*>(patch_stack) - patch_stack_size); } static void InitializePatchContextSlots() { ASSERT_MSG(pthread_key_create(&stack_pointer_slot, nullptr) == 0, "Unable to allocate thread-local register for stack pointer."); ASSERT_MSG(pthread_key_create(&patch_stack_slot, FreePatchStack) == 0, "Unable to allocate thread-local register for patch stack."); } void InitializeThreadPatchStack() { std::call_once(patch_context_slots_init_flag, InitializePatchContextSlots); pthread_setspecific(patch_stack_slot, static_cast<u8*>(std::malloc(patch_stack_size)) + patch_stack_size); } /// Saves the stack pointer to thread local storage and loads the patch stack. static void SaveStack(Xbyak::CodeGenerator& c) { std::call_once(patch_context_slots_init_flag, InitializePatchContextSlots); // Save original stack pointer and load patch stack. c.putSeg(gs); c.mov(qword[reinterpret_cast<void*>(stack_pointer_slot * sizeof(void*))], rsp); c.putSeg(gs); c.mov(rsp, qword[reinterpret_cast<void*>(patch_stack_slot * sizeof(void*))]); } /// Restores the stack pointer from thread local storage. static void RestoreStack(Xbyak::CodeGenerator& c) { std::call_once(patch_context_slots_init_flag, InitializePatchContextSlots); // Save patch stack pointer and load original stack. c.putSeg(gs); c.mov(qword[reinterpret_cast<void*>(patch_stack_slot * sizeof(void*))], rsp); c.putSeg(gs); c.mov(rsp, qword[reinterpret_cast<void*>(stack_pointer_slot * sizeof(void*))]); } #else // These utilities are not implemented as we can't save anything to thread local storage without // temporary registers. void InitializeThreadPatchStack() { // No-op } /// Saves the stack pointer to thread local storage and loads the patch stack. static void SaveStack(Xbyak::CodeGenerator& c) { UNIMPLEMENTED(); } /// Restores the stack pointer from thread local storage. static void RestoreStack(Xbyak::CodeGenerator& c) { UNIMPLEMENTED(); } #endif /// Switches to the patch stack, saves registers, and restores the original stack. static void SaveRegisters(Xbyak::CodeGenerator& c, const std::initializer_list<Xbyak::Reg> regs) { SaveStack(c); for (const auto& reg : regs) { c.push(reg.cvt64()); } RestoreStack(c); } /// Switches to the patch stack, restores registers, and restores the original stack. static void RestoreRegisters(Xbyak::CodeGenerator& c, const std::initializer_list<Xbyak::Reg> regs) { SaveStack(c); for (const auto& reg : regs) { c.pop(reg.cvt64()); } RestoreStack(c); } /// Switches to the patch stack and stores all registers. static void SaveContext(Xbyak::CodeGenerator& c, bool save_flags = false) { SaveStack(c); for (int reg = Xbyak::Operand::RAX; reg <= Xbyak::Operand::R15; reg++) { c.push(Xbyak::Reg64(reg)); } for (int reg = 0; reg <= 7; reg++) { c.lea(rsp, ptr[rsp - 32]); c.vmovdqu(ptr[rsp], Xbyak::Ymm(reg)); } if (save_flags) { c.pushfq(); } } /// Restores all registers and restores the original stack. /// If the destination is a register, it is not restored to preserve the output. static void RestoreContext(Xbyak::CodeGenerator& c, const Xbyak::Operand& dst, bool restore_flags = false) { if (restore_flags) { c.popfq(); } for (int reg = 7; reg >= 0; reg--) { if ((!dst.isXMM() && !dst.isYMM()) || dst.getIdx() != reg) { c.vmovdqu(Xbyak::Ymm(reg), ptr[rsp]); } c.lea(rsp, ptr[rsp + 32]); } for (int reg = Xbyak::Operand::R15; reg >= Xbyak::Operand::RAX; reg--) { if (!dst.isREG() || dst.getIdx() != reg) { c.pop(Xbyak::Reg64(reg)); } else { c.lea(rsp, ptr[rsp + 8]); } } RestoreStack(c); } #ifdef __APPLE__ static void GenerateANDN(const ZydisDecodedOperand* operands, Xbyak::CodeGenerator& c) { const auto dst = ZydisToXbyakRegisterOperand(operands[0]); const auto src1 = ZydisToXbyakRegisterOperand(operands[1]); const auto src2 = ZydisToXbyakOperand(operands[2]); const auto scratch = AllocateScratchRegister({&dst, &src1, src2.get()}, dst.getBit()); SaveRegisters(c, {scratch}); c.mov(scratch, src1); c.not_(scratch); c.and_(scratch, *src2); c.mov(dst, scratch); RestoreRegisters(c, {scratch}); } static void GenerateBEXTR(const ZydisDecodedOperand* operands, Xbyak::CodeGenerator& c) { const auto dst = ZydisToXbyakRegisterOperand(operands[0]); const auto src = ZydisToXbyakOperand(operands[1]); const auto start_len = ZydisToXbyakRegisterOperand(operands[2]); const Xbyak::Reg32e shift(Xbyak::Operand::RCX, static_cast<int>(start_len.getBit())); const auto scratch1 = AllocateScratchRegister({&dst, src.get(), &start_len, &shift}, dst.getBit()); const auto scratch2 = AllocateScratchRegister({&dst, src.get(), &start_len, &shift, &scratch1}, dst.getBit()); if (dst.getIdx() == shift.getIdx()) { SaveRegisters(c, {scratch1, scratch2}); } else { SaveRegisters(c, {scratch1, scratch2, shift}); } c.mov(scratch1, *src); if (shift.getIdx() != start_len.getIdx()) { c.mov(shift, start_len); } c.shr(scratch1, shift.cvt8()); c.shr(shift, 8); c.mov(scratch2, 1); c.shl(scratch2, shift.cvt8()); c.dec(scratch2); c.mov(dst, scratch1); c.and_(dst, scratch2); if (dst.getIdx() == shift.getIdx()) { RestoreRegisters(c, {scratch2, scratch1}); } else { RestoreRegisters(c, {shift, scratch2, scratch1}); } } static void GenerateBLSI(const ZydisDecodedOperand* operands, Xbyak::CodeGenerator& c) { const auto dst = ZydisToXbyakRegisterOperand(operands[0]); const auto src = ZydisToXbyakOperand(operands[1]); const auto scratch = AllocateScratchRegister({&dst, src.get()}, dst.getBit()); SaveRegisters(c, {scratch}); // BLSI sets CF to zero if source is zero, otherwise it sets CF to one. Xbyak::Label clear_carry, end; c.mov(scratch, *src); c.neg(scratch); // NEG, like BLSI, clears CF if the source is zero and sets it otherwise c.jnc(clear_carry); c.and_(scratch, *src); c.stc(); // setting/clearing carry needs to happen after the AND because that clears CF c.jmp(end); c.L(clear_carry); c.and_(scratch, *src); // We don't need to clear carry here since AND does that for us c.L(end); c.mov(dst, scratch); RestoreRegisters(c, {scratch}); } static void GenerateBLSMSK(const ZydisDecodedOperand* operands, Xbyak::CodeGenerator& c) { const auto dst = ZydisToXbyakRegisterOperand(operands[0]); const auto src = ZydisToXbyakOperand(operands[1]); const auto scratch = AllocateScratchRegister({&dst, src.get()}, dst.getBit()); SaveRegisters(c, {scratch}); Xbyak::Label clear_carry, end; // BLSMSK sets CF to zero if source is NOT zero, otherwise it sets CF to one. c.mov(scratch, *src); c.test(scratch, scratch); c.jnz(clear_carry); c.dec(scratch); c.xor_(scratch, *src); c.stc(); c.jmp(end); c.L(clear_carry); c.dec(scratch); c.xor_(scratch, *src); // We don't need to clear carry here since XOR does that for us c.L(end); c.mov(dst, scratch); RestoreRegisters(c, {scratch}); } static void GenerateBLSR(const ZydisDecodedOperand* operands, Xbyak::CodeGenerator& c) { const auto dst = ZydisToXbyakRegisterOperand(operands[0]); const auto src = ZydisToXbyakOperand(operands[1]); const auto scratch = AllocateScratchRegister({&dst, src.get()}, dst.getBit()); SaveRegisters(c, {scratch}); Xbyak::Label clear_carry, end; // BLSR sets CF to zero if source is NOT zero, otherwise it sets CF to one. c.mov(scratch, *src); c.test(scratch, scratch); c.jnz(clear_carry); c.dec(scratch); c.and_(scratch, *src); c.stc(); c.jmp(end); c.L(clear_carry); c.dec(scratch); c.and_(scratch, *src); // We don't need to clear carry here since AND does that for us c.L(end); c.mov(dst, scratch); RestoreRegisters(c, {scratch}); } static __attribute__((sysv_abi)) void PerformVCVTPH2PS(float* out, const half_float::half* in, const u32 count) { for (u32 i = 0; i < count; i++) { out[i] = half_float::half_cast<float>(in[i]); } } static void GenerateVCVTPH2PS(const ZydisDecodedOperand* operands, Xbyak::CodeGenerator& c) { const auto dst = ZydisToXbyakRegisterOperand(operands[0]); const auto src = ZydisToXbyakOperand(operands[1]); const auto float_count = dst.getBit() / 32; const auto byte_count = float_count * 4; SaveContext(c, true); // Allocate stack space for outputs and load into first parameter. c.sub(rsp, byte_count); c.mov(rdi, rsp); if (src->isXMM()) { // Allocate stack space for inputs and load into second parameter. c.sub(rsp, byte_count); c.mov(rsi, rsp); // Move input to the allocated space. c.movdqu(ptr[rsp], *reinterpret_cast<Xbyak::Xmm*>(src.get())); } else { c.lea(rsi, src->getAddress()); } // Load float count into third parameter. c.mov(rdx, float_count); c.mov(rax, reinterpret_cast<u64>(PerformVCVTPH2PS)); c.call(rax); if (src->isXMM()) { // Clean up after inputs space. c.add(rsp, byte_count); } // Load outputs into destination register and clean up space. if (dst.isYMM()) { c.vmovdqu(*reinterpret_cast<const Xbyak::Ymm*>(&dst), ptr[rsp]); } else { c.movdqu(*reinterpret_cast<const Xbyak::Xmm*>(&dst), ptr[rsp]); } c.add(rsp, byte_count); RestoreContext(c, dst, true); } using SingleToHalfFloatConverter = half_float::half (*)(float); static const SingleToHalfFloatConverter SingleToHalfFloatConverters[4] = { half_float::half_cast<half_float::half, std::round_to_nearest, float>, half_float::half_cast<half_float::half, std::round_toward_neg_infinity, float>, half_float::half_cast<half_float::half, std::round_toward_infinity, float>, half_float::half_cast<half_float::half, std::round_toward_zero, float>, }; static __attribute__((sysv_abi)) void PerformVCVTPS2PH(half_float::half* out, const float* in, const u32 count, const u8 rounding_mode) { const auto conversion_func = SingleToHalfFloatConverters[rounding_mode]; for (u32 i = 0; i < count; i++) { out[i] = conversion_func(in[i]); } } static void GenerateVCVTPS2PH(const ZydisDecodedOperand* operands, Xbyak::CodeGenerator& c) { const auto dst = ZydisToXbyakOperand(operands[0]); const auto src = ZydisToXbyakRegisterOperand(operands[1]); const auto ctrl = ZydisToXbyakImmediateOperand(operands[2]); const auto float_count = src.getBit() / 32; const auto byte_count = float_count * 4; SaveContext(c, true); if (dst->isXMM()) { // Allocate stack space for outputs and load into first parameter. c.sub(rsp, byte_count); c.mov(rdi, rsp); } else { c.lea(rdi, dst->getAddress()); } // Allocate stack space for inputs and load into second parameter. c.sub(rsp, byte_count); c.mov(rsi, rsp); // Move input to the allocated space. if (src.isYMM()) { c.vmovdqu(ptr[rsp], *reinterpret_cast<const Xbyak::Ymm*>(&src)); } else { c.movdqu(ptr[rsp], *reinterpret_cast<const Xbyak::Xmm*>(&src)); } // Load float count into third parameter. c.mov(rdx, float_count); // Load rounding mode into fourth parameter. if (ctrl & 4) { // Load from MXCSR.RC. c.stmxcsr(ptr[rsp - 4]); c.mov(rcx, ptr[rsp - 4]); c.shr(rcx, 13); c.and_(rcx, 3); } else { c.mov(rcx, ctrl & 3); } c.mov(rax, reinterpret_cast<u64>(PerformVCVTPS2PH)); c.call(rax); // Clean up after inputs space. c.add(rsp, byte_count); if (dst->isXMM()) { // Load outputs into destination register and clean up space. c.movdqu(*reinterpret_cast<Xbyak::Xmm*>(dst.get()), ptr[rsp]); c.add(rsp, byte_count); } RestoreContext(c, *dst, true); } static bool FilterRosetta2Only(const ZydisDecodedOperand*) { int ret = 0; size_t size = sizeof(ret); if (sysctlbyname("sysctl.proc_translated", &ret, &size, nullptr, 0) != 0) { return false; } return ret; } #else // __APPLE__ static bool FilterTcbAccess(const ZydisDecodedOperand* operands) { const auto& dst_op = operands[0]; const auto& src_op = operands[1]; // Patch only 'mov (64-bit register), fs:[0]' return src_op.type == ZYDIS_OPERAND_TYPE_MEMORY && src_op.mem.segment == ZYDIS_REGISTER_FS && src_op.mem.base == ZYDIS_REGISTER_NONE && src_op.mem.index == ZYDIS_REGISTER_NONE && src_op.mem.disp.value == 0 && dst_op.reg.value >= ZYDIS_REGISTER_RAX && dst_op.reg.value <= ZYDIS_REGISTER_R15; } static void GenerateTcbAccess(const ZydisDecodedOperand* operands, Xbyak::CodeGenerator& c) { const auto dst = ZydisToXbyakRegisterOperand(operands[0]); #if defined(_WIN32) // The following logic is based on the Kernel32.dll asm of TlsGetValue static constexpr u32 TlsSlotsOffset = 0x1480; static constexpr u32 TlsExpansionSlotsOffset = 0x1780; static constexpr u32 TlsMinimumAvailable = 64; const auto slot = GetTcbKey(); // Load the pointer to the table of TLS slots. c.putSeg(gs); if (slot < TlsMinimumAvailable) { // Load the pointer to TLS slots. c.mov(dst, ptr[reinterpret_cast<void*>(TlsSlotsOffset + slot * sizeof(LPVOID))]); } else { const u32 tls_index = slot - TlsMinimumAvailable; // Load the pointer to the table of TLS expansion slots. c.mov(dst, ptr[reinterpret_cast<void*>(TlsExpansionSlotsOffset)]); // Load the pointer to our buffer. c.mov(dst, qword[dst + tls_index * sizeof(LPVOID)]); } #else const auto src = ZydisToXbyakMemoryOperand(operands[1]); // Replace fs read with gs read. c.putSeg(gs); c.mov(dst, src); #endif } #endif // __APPLE__ static bool FilterNoSSE4a(const ZydisDecodedOperand*) { Cpu cpu; return !cpu.has(Cpu::tSSE4a); } static void GenerateEXTRQ(const ZydisDecodedOperand* operands, Xbyak::CodeGenerator& c) { bool immediateForm = operands[1].type == ZYDIS_OPERAND_TYPE_IMMEDIATE && operands[2].type == ZYDIS_OPERAND_TYPE_IMMEDIATE; ASSERT_MSG(operands[0].type == ZYDIS_OPERAND_TYPE_REGISTER, "operand 0 must be a register"); const auto dst = ZydisToXbyakRegisterOperand(operands[0]); ASSERT_MSG(dst.isXMM(), "operand 0 must be an XMM register"); Xbyak::Xmm xmm_dst = *reinterpret_cast<const Xbyak::Xmm*>(&dst); if (immediateForm) { u8 length = operands[1].imm.value.u & 0x3F; u8 index = operands[2].imm.value.u & 0x3F; LOG_DEBUG(Core, "Patching immediate form EXTRQ, length: {}, index: {}", length, index); const Xbyak::Reg64 scratch1 = rax; const Xbyak::Reg64 scratch2 = rcx; // Set rsp to before red zone and save scratch registers c.lea(rsp, ptr[rsp - 128]); c.pushfq(); c.push(scratch1); c.push(scratch2); u64 mask; if (length == 0) { length = 64; // for the check below mask = 0xFFFF'FFFF'FFFF'FFFF; } else { mask = (1ULL << length) - 1; } ASSERT_MSG(length + index <= 64, "length + index must be less than or equal to 64."); // Get lower qword from xmm register MAYBE_AVX(movq, scratch1, xmm_dst); if (index != 0) { c.shr(scratch1, index); } // We need to move mask to a register because we can't use all the possible // immediate values with `and reg, imm32` c.mov(scratch2, mask); c.and_(scratch1, scratch2); // Writeback to xmm register, extrq instruction says top 64-bits are undefined so we don't // care to preserve them MAYBE_AVX(movq, xmm_dst, scratch1); c.pop(scratch2); c.pop(scratch1); c.popfq(); c.lea(rsp, ptr[rsp + 128]); } else { ASSERT_MSG(operands[0].type == ZYDIS_OPERAND_TYPE_REGISTER && operands[1].type == ZYDIS_OPERAND_TYPE_REGISTER && operands[0].reg.value >= ZYDIS_REGISTER_XMM0 && operands[0].reg.value <= ZYDIS_REGISTER_XMM15 && operands[1].reg.value >= ZYDIS_REGISTER_XMM0 && operands[1].reg.value <= ZYDIS_REGISTER_XMM15, "Unexpected operand types for EXTRQ instruction"); const auto src = ZydisToXbyakRegisterOperand(operands[1]); ASSERT_MSG(src.isXMM(), "operand 1 must be an XMM register"); Xbyak::Xmm xmm_src = *reinterpret_cast<const Xbyak::Xmm*>(&src); const Xbyak::Reg64 scratch1 = rax; const Xbyak::Reg64 scratch2 = rcx; const Xbyak::Reg64 mask = rdx; Xbyak::Label length_zero, end; c.lea(rsp, ptr[rsp - 128]); c.pushfq(); c.push(scratch1); c.push(scratch2); c.push(mask); // Construct the mask out of the length that resides in bottom 6 bits of source xmm MAYBE_AVX(movq, scratch1, xmm_src); c.mov(scratch2, scratch1); c.and_(scratch2, 0x3F); c.jz(length_zero); // mask = (1ULL << length) - 1 c.mov(mask, 1); c.shl(mask, cl); c.dec(mask); c.jmp(end); c.L(length_zero); c.mov(mask, 0xFFFF'FFFF'FFFF'FFFF); c.L(end); // Get the shift amount and store it in scratch2 c.shr(scratch1, 8); c.and_(scratch1, 0x3F); c.mov(scratch2, scratch1); // cl now contains the shift amount MAYBE_AVX(movq, scratch1, xmm_dst); c.shr(scratch1, cl); c.and_(scratch1, mask); MAYBE_AVX(movq, xmm_dst, scratch1); c.pop(mask); c.pop(scratch2); c.pop(scratch1); c.popfq(); c.lea(rsp, ptr[rsp + 128]); } } static void GenerateINSERTQ(const ZydisDecodedOperand* operands, Xbyak::CodeGenerator& c) { bool immediateForm = operands[2].type == ZYDIS_OPERAND_TYPE_IMMEDIATE && operands[3].type == ZYDIS_OPERAND_TYPE_IMMEDIATE; ASSERT_MSG(operands[0].type == ZYDIS_OPERAND_TYPE_REGISTER && operands[1].type == ZYDIS_OPERAND_TYPE_REGISTER, "operands 0 and 1 must be registers."); const auto dst = ZydisToXbyakRegisterOperand(operands[0]); const auto src = ZydisToXbyakRegisterOperand(operands[1]); ASSERT_MSG(dst.isXMM() && src.isXMM(), "operands 0 and 1 must be xmm registers."); Xbyak::Xmm xmm_dst = *reinterpret_cast<const Xbyak::Xmm*>(&dst); Xbyak::Xmm xmm_src = *reinterpret_cast<const Xbyak::Xmm*>(&src); if (immediateForm) { u8 length = operands[2].imm.value.u & 0x3F; u8 index = operands[3].imm.value.u & 0x3F; const Xbyak::Reg64 scratch1 = rax; const Xbyak::Reg64 scratch2 = rcx; const Xbyak::Reg64 mask = rdx; // Set rsp to before red zone and save scratch registers c.lea(rsp, ptr[rsp - 128]); c.pushfq(); c.push(scratch1); c.push(scratch2); c.push(mask); u64 mask_value; if (length == 0) { length = 64; // for the check below mask_value = 0xFFFF'FFFF'FFFF'FFFF; } else { mask_value = (1ULL << length) - 1; } ASSERT_MSG(length + index <= 64, "length + index must be less than or equal to 64."); MAYBE_AVX(movq, scratch1, xmm_src); MAYBE_AVX(movq, scratch2, xmm_dst); c.mov(mask, mask_value); // src &= mask c.and_(scratch1, mask); // src <<= index c.shl(scratch1, index); // dst &= ~(mask << index) mask_value = ~(mask_value << index); c.mov(mask, mask_value); c.and_(scratch2, mask); // dst |= src c.or_(scratch2, scratch1); // Insert scratch2 into low 64 bits of dst, upper 64 bits are unaffected Cpu cpu; if (cpu.has(Cpu::tAVX)) { c.vpinsrq(xmm_dst, xmm_dst, scratch2, 0); } else { c.pinsrq(xmm_dst, scratch2, 0); } c.pop(mask); c.pop(scratch2); c.pop(scratch1); c.popfq(); c.lea(rsp, ptr[rsp + 128]); } else { ASSERT_MSG(operands[2].type == ZYDIS_OPERAND_TYPE_UNUSED && operands[3].type == ZYDIS_OPERAND_TYPE_UNUSED, "operands 2 and 3 must be unused for register form."); const Xbyak::Reg64 scratch1 = rax; const Xbyak::Reg64 scratch2 = rcx; const Xbyak::Reg64 index = rdx; const Xbyak::Reg64 mask = rbx; Xbyak::Label length_zero, end; c.lea(rsp, ptr[rsp - 128]); c.pushfq(); c.push(scratch1); c.push(scratch2); c.push(index); c.push(mask); // Get upper 64 bits of src and copy it to mask and index MAYBE_AVX(pextrq, index, xmm_src, 1); c.mov(mask, index); // When length is 0, set it to 64 c.and_(mask, 0x3F); // mask now holds the length c.jz(length_zero); // Check if length is 0 and set mask to all 1s if it is // Create a mask out of the length c.mov(cl, mask.cvt8()); c.mov(mask, 1); c.shl(mask, cl); c.dec(mask); c.jmp(end); c.L(length_zero); c.mov(mask, 0xFFFF'FFFF'FFFF'FFFF); c.L(end); // Get index to insert at c.shr(index, 8); c.and_(index, 0x3F); // src &= mask MAYBE_AVX(movq, scratch1, xmm_src); c.and_(scratch1, mask); // mask = ~(mask << index) c.mov(cl, index.cvt8()); c.shl(mask, cl); c.not_(mask); // src <<= index c.shl(scratch1, cl); // dst = (dst & mask) | src MAYBE_AVX(movq, scratch2, xmm_dst); c.and_(scratch2, mask); c.or_(scratch2, scratch1); // Upper 64 bits are undefined in insertq MAYBE_AVX(movq, xmm_dst, scratch2); c.pop(mask); c.pop(index); c.pop(scratch2); c.pop(scratch1); c.popfq(); c.lea(rsp, ptr[rsp + 128]); } } using PatchFilter = bool (*)(const ZydisDecodedOperand*); using InstructionGenerator = void (*)(const ZydisDecodedOperand*, Xbyak::CodeGenerator&); struct PatchInfo { /// Filter for more granular patch conditions past just the instruction mnemonic. PatchFilter filter; /// Generator for the patch/trampoline. InstructionGenerator generator; /// Whether to use a trampoline for this patch. bool trampoline; }; static const std::unordered_map<ZydisMnemonic, PatchInfo> Patches = { #if defined(_WIN32) // Windows needs a trampoline. {ZYDIS_MNEMONIC_MOV, {FilterTcbAccess, GenerateTcbAccess, true}}, #elif !defined(__APPLE__) {ZYDIS_MNEMONIC_MOV, {FilterTcbAccess, GenerateTcbAccess, false}}, #endif {ZYDIS_MNEMONIC_EXTRQ, {FilterNoSSE4a, GenerateEXTRQ, true}}, {ZYDIS_MNEMONIC_INSERTQ, {FilterNoSSE4a, GenerateINSERTQ, true}}, #ifdef __APPLE__ // Patches for instruction sets not supported by Rosetta 2. // BMI1 {ZYDIS_MNEMONIC_ANDN, {FilterRosetta2Only, GenerateANDN, true}}, {ZYDIS_MNEMONIC_BEXTR, {FilterRosetta2Only, GenerateBEXTR, true}}, {ZYDIS_MNEMONIC_BLSI, {FilterRosetta2Only, GenerateBLSI, true}}, {ZYDIS_MNEMONIC_BLSMSK, {FilterRosetta2Only, GenerateBLSMSK, true}}, {ZYDIS_MNEMONIC_BLSR, {FilterRosetta2Only, GenerateBLSR, true}}, // F16C {ZYDIS_MNEMONIC_VCVTPH2PS, {FilterRosetta2Only, GenerateVCVTPH2PS, true}}, {ZYDIS_MNEMONIC_VCVTPS2PH, {FilterRosetta2Only, GenerateVCVTPS2PH, true}}, #endif }; static std::once_flag init_flag; struct PatchModule { /// Mutex controlling access to module code regions. std::mutex mutex{}; /// Start of the module. u8* start; /// End of the module. u8* end; /// Tracker for patched code locations. std::set<u8*> patched; /// Code generator for patching the module. Xbyak::CodeGenerator patch_gen; /// Code generator for writing trampoline patches. Xbyak::CodeGenerator trampoline_gen; PatchModule(u8* module_ptr, const u64 module_size, u8* trampoline_ptr, const u64 trampoline_size) : start(module_ptr), end(module_ptr + module_size), patch_gen(module_size, module_ptr), trampoline_gen(trampoline_size, trampoline_ptr) {} }; static std::map<u64, PatchModule> modules; static PatchModule* GetModule(const void* ptr) { auto upper_bound = modules.upper_bound(reinterpret_cast<u64>(ptr)); if (upper_bound == modules.begin()) { return nullptr; } return &(std::prev(upper_bound)->second); } /// Returns a boolean indicating whether the instruction was patched, and the offset to advance past /// whatever is at the current code pointer. static std::pair<bool, u64> TryPatch(u8* code, PatchModule* module) { ZydisDecodedInstruction instruction; ZydisDecodedOperand operands[ZYDIS_MAX_OPERAND_COUNT]; const auto status = Common::Decoder::Instance()->decodeInstruction(instruction, operands, code, module->end - code); if (!ZYAN_SUCCESS(status)) { return std::make_pair(false, 1); } if (Patches.contains(instruction.mnemonic)) { const auto& patch_info = Patches.at(instruction.mnemonic); bool needs_trampoline = patch_info.trampoline; if (patch_info.filter(operands)) { auto& patch_gen = module->patch_gen; if (needs_trampoline && instruction.length < 5) { // Trampoline is needed but instruction is too short to patch. // Return false and length to fall back to the illegal instruction handler, // or to signal to AOT compilation that this instruction should be skipped and // handled at runtime. return std::make_pair(false, instruction.length); } // Reset state and move to current code position. patch_gen.reset(); patch_gen.setSize(code - patch_gen.getCode()); if (needs_trampoline) { auto& trampoline_gen = module->trampoline_gen; const auto trampoline_ptr = trampoline_gen.getCurr(); patch_info.generator(operands, trampoline_gen); // Return to the following instruction at the end of the trampoline. trampoline_gen.jmp(code + instruction.length); // Replace instruction with near jump to the trampoline. patch_gen.jmp(trampoline_ptr, Xbyak::CodeGenerator::LabelType::T_NEAR); } else { patch_info.generator(operands, patch_gen); } const auto patch_size = patch_gen.getCurr() - code; if (patch_size > 0) { ASSERT_MSG(instruction.length >= patch_size, "Instruction {} with length {} is too short to replace at: {}", ZydisMnemonicGetString(instruction.mnemonic), instruction.length, fmt::ptr(code)); // Fill remaining space with nops. patch_gen.nop(instruction.length - patch_size); module->patched.insert(code); LOG_DEBUG(Core, "Patched instruction '{}' at: {}", ZydisMnemonicGetString(instruction.mnemonic), fmt::ptr(code)); return std::make_pair(true, instruction.length); } } } return std::make_pair(false, instruction.length); } #if defined(ARCH_X86_64) static bool TryExecuteIllegalInstruction(void* ctx, void* code_address) { ZydisDecodedInstruction instruction; ZydisDecodedOperand operands[ZYDIS_MAX_OPERAND_COUNT]; const auto status = Common::Decoder::Instance()->decodeInstruction(instruction, operands, code_address); switch (instruction.mnemonic) { case ZYDIS_MNEMONIC_EXTRQ: { bool immediateForm = operands[1].type == ZYDIS_OPERAND_TYPE_IMMEDIATE && operands[2].type == ZYDIS_OPERAND_TYPE_IMMEDIATE; if (immediateForm) { LOG_CRITICAL(Core, "EXTRQ immediate form should have been patched at code address: {}", fmt::ptr(code_address)); return false; } else { ASSERT_MSG(operands[0].type == ZYDIS_OPERAND_TYPE_REGISTER && operands[1].type == ZYDIS_OPERAND_TYPE_REGISTER && operands[0].reg.value >= ZYDIS_REGISTER_XMM0 && operands[0].reg.value <= ZYDIS_REGISTER_XMM15 && operands[1].reg.value >= ZYDIS_REGISTER_XMM0 && operands[1].reg.value <= ZYDIS_REGISTER_XMM15, "Unexpected operand types for EXTRQ instruction"); const auto dstIndex = operands[0].reg.value - ZYDIS_REGISTER_XMM0; const auto srcIndex = operands[1].reg.value - ZYDIS_REGISTER_XMM0; const auto dst = Common::GetXmmPointer(ctx, dstIndex); const auto src = Common::GetXmmPointer(ctx, srcIndex); u64 lowQWordSrc; memcpy(&lowQWordSrc, src, sizeof(lowQWordSrc)); u64 lowQWordDst; memcpy(&lowQWordDst, dst, sizeof(lowQWordDst)); u64 length = lowQWordSrc & 0x3F; u64 mask; if (length == 0) { length = 64; // for the check below mask = 0xFFFF'FFFF'FFFF'FFFF; } else { mask = (1ULL << length) - 1; } u64 index = (lowQWordSrc >> 8) & 0x3F; if (length + index > 64) { // Undefined behavior if length + index is bigger than 64 according to the spec, // we'll warn and continue execution. LOG_WARNING(Core, "extrq at {} with length {} and index {} is bigger than 64, " "undefined behavior", fmt::ptr(code_address), length, index); } lowQWordDst >>= index; lowQWordDst &= mask; memcpy(dst, &lowQWordDst, sizeof(lowQWordDst)); Common::IncrementRip(ctx, instruction.length); return true; } break; } case ZYDIS_MNEMONIC_INSERTQ: { bool immediateForm = operands[2].type == ZYDIS_OPERAND_TYPE_IMMEDIATE && operands[3].type == ZYDIS_OPERAND_TYPE_IMMEDIATE; if (immediateForm) { LOG_CRITICAL(Core, "INSERTQ immediate form should have been patched at code address: {}", fmt::ptr(code_address)); return false; } else { ASSERT_MSG(operands[2].type == ZYDIS_OPERAND_TYPE_UNUSED && operands[3].type == ZYDIS_OPERAND_TYPE_UNUSED, "operands 2 and 3 must be unused for register form."); ASSERT_MSG(operands[0].type == ZYDIS_OPERAND_TYPE_REGISTER && operands[1].type == ZYDIS_OPERAND_TYPE_REGISTER, "operands 0 and 1 must be registers."); const auto dstIndex = operands[0].reg.value - ZYDIS_REGISTER_XMM0; const auto srcIndex = operands[1].reg.value - ZYDIS_REGISTER_XMM0; const auto dst = Common::GetXmmPointer(ctx, dstIndex); const auto src = Common::GetXmmPointer(ctx, srcIndex); u64 lowQWordSrc, highQWordSrc; memcpy(&lowQWordSrc, src, sizeof(lowQWordSrc)); memcpy(&highQWordSrc, (u8*)src + 8, sizeof(highQWordSrc)); u64 lowQWordDst; memcpy(&lowQWordDst, dst, sizeof(lowQWordDst)); u64 length = highQWordSrc & 0x3F; u64 mask; if (length == 0) { length = 64; // for the check below mask = 0xFFFF'FFFF'FFFF'FFFF; } else { mask = (1ULL << length) - 1; } u64 index = (highQWordSrc >> 8) & 0x3F; if (length + index > 64) { // Undefined behavior if length + index is bigger than 64 according to the spec, // we'll warn and continue execution. LOG_WARNING(Core, "insertq at {} with length {} and index {} is bigger than 64, " "undefined behavior", fmt::ptr(code_address), length, index); } lowQWordSrc &= mask; lowQWordDst &= ~(mask << index); lowQWordDst |= lowQWordSrc << index; memcpy(dst, &lowQWordDst, sizeof(lowQWordDst)); Common::IncrementRip(ctx, instruction.length); return true; } break; } default: { LOG_ERROR(Core, "Unhandled illegal instruction at code address {}: {}", fmt::ptr(code_address), ZydisMnemonicGetString(instruction.mnemonic)); return false; } } UNREACHABLE(); } #elif defined(ARCH_ARM64) // These functions shouldn't be needed for ARM as it will use a JIT so there's no need to patch // instructions. static bool TryExecuteIllegalInstruction(void*, void*) { return false; } #else #error "Unsupported architecture" #endif static bool TryPatchJit(void* code_address) { auto* code = static_cast<u8*>(code_address); auto* module = GetModule(code); if (module == nullptr) { return false; } std::unique_lock lock{module->mutex}; // Return early if already patched, in case multiple threads signaled at the same time. if (std::ranges::find(module->patched, code) != module->patched.end()) { return true; } return TryPatch(code, module).first; } static void TryPatchAot(void* code_address, u64 code_size) { auto* code = static_cast<u8*>(code_address); auto* module = GetModule(code); if (module == nullptr) { return; } std::unique_lock lock{module->mutex}; const auto* end = code + code_size; while (code < end) { code += TryPatch(code, module).second; } } static bool PatchesAccessViolationHandler(void* context, void* /* fault_address */) { return TryPatchJit(Common::GetRip(context)); } static bool PatchesIllegalInstructionHandler(void* context) { void* code_address = Common::GetRip(context); if (!TryPatchJit(code_address)) { return TryExecuteIllegalInstruction(context, code_address); } return true; } static void PatchesInit() { if (!Patches.empty()) { auto* signals = Signals::Instance(); // Should be called last. constexpr auto priority = std::numeric_limits<u32>::max(); signals->RegisterAccessViolationHandler(PatchesAccessViolationHandler, priority); signals->RegisterIllegalInstructionHandler(PatchesIllegalInstructionHandler, priority); } } void RegisterPatchModule(void* module_ptr, u64 module_size, void* trampoline_area_ptr, u64 trampoline_area_size) { std::call_once(init_flag, PatchesInit); const auto module_addr = reinterpret_cast<u64>(module_ptr); modules.emplace(std::piecewise_construct, std::forward_as_tuple(module_addr), std::forward_as_tuple(static_cast<u8*>(module_ptr), module_size, static_cast<u8*>(trampoline_area_ptr), trampoline_area_size)); } void PrePatchInstructions(u64 segment_addr, u64 segment_size) { #if defined(__APPLE__) // HACK: For some reason patching in the signal handler at the start of a page does not work // under Rosetta 2. Patch any instructions at the start of a page ahead of time. if (!Patches.empty()) { auto* code_page = reinterpret_cast<u8*>(Common::AlignUp(segment_addr, 0x1000)); const auto* end_page = code_page + Common::AlignUp(segment_size, 0x1000); while (code_page < end_page) { TryPatchJit(code_page); code_page += 0x1000; } } #elif !defined(_WIN32) // Linux and others have an FS segment pointing to valid memory, so continue to do full // ahead-of-time patching for now until a better solution is worked out. if (!Patches.empty()) { TryPatchAot(reinterpret_cast<void*>(segment_addr), segment_size); } #endif } } // namespace Core
43,136
C++
.cpp
1,000
35.16
100
0.616174
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,540
linker.cpp
shadps4-emu_shadPS4/src/core/linker.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/alignment.h" #include "common/arch.h" #include "common/assert.h" #include "common/config.h" #include "common/logging/log.h" #include "common/path_util.h" #include "common/string_util.h" #include "common/thread.h" #include "core/aerolib/aerolib.h" #include "core/aerolib/stubs.h" #include "core/cpu_patches.h" #include "core/libraries/kernel/memory_management.h" #include "core/libraries/kernel/thread_management.h" #include "core/linker.h" #include "core/memory.h" #include "core/tls.h" #include "core/virtual_memory.h" #include "debug_state.h" namespace Core { using ExitFunc = PS4_SYSV_ABI void (*)(); static PS4_SYSV_ABI void ProgramExitFunc() { fmt::print("exit function called\n"); } #ifdef ARCH_X86_64 static PS4_SYSV_ABI void RunMainEntry(VAddr addr, EntryParams* params, ExitFunc exit_func) { // reinterpret_cast<entry_func_t>(addr)(params, exit_func); // can't be used, stack has to have // a specific layout asm volatile("andq $-16, %%rsp\n" // Align to 16 bytes "subq $8, %%rsp\n" // videoout_basic expects the stack to be misaligned // Kernel also pushes some more things here during process init // at least: environment, auxv, possibly other things "pushq 8(%1)\n" // copy EntryParams to top of stack like the kernel does "pushq 0(%1)\n" // OpenOrbis expects to find it there "movq %1, %%rdi\n" // also pass params and exit func "movq %2, %%rsi\n" // as before "jmp *%0\n" // can't use call here, as that would mangle the prepared stack. // there's no coming back : : "r"(addr), "r"(params), "r"(exit_func) : "rax", "rsi", "rdi"); } #endif Linker::Linker() : memory{Memory::Instance()} {} Linker::~Linker() = default; void Linker::Execute() { if (Config::debugDump()) { DebugDump(); } // Calculate static TLS size. for (const auto& module : m_modules) { static_tls_size += module->tls.image_size; module->tls.offset = static_tls_size; } // Relocate all modules for (const auto& m : m_modules) { Relocate(m.get()); } // Configure used flexible memory size. if (const auto* proc_param = GetProcParam()) { if (proc_param->size >= offsetof(OrbisProcParam, mem_param) + sizeof(OrbisKernelMemParam*)) { if (const auto* mem_param = proc_param->mem_param) { if (mem_param->size >= offsetof(OrbisKernelMemParam, flexible_memory_size) + sizeof(u64*)) { if (const auto* flexible_size = mem_param->flexible_memory_size) { memory->SetupMemoryRegions(*flexible_size); } } } } } // Init primary thread. Common::SetCurrentThreadName("GAME_MainThread"); DebugState.AddCurrentThreadToGuestList(); Libraries::Kernel::pthreadInitSelfMainThread(); EnsureThreadInitialized(true); // Start shared library modules for (auto& m : m_modules) { if (m->IsSharedLib()) { m->Start(0, nullptr, nullptr); } } // Start main module. EntryParams p{}; p.argc = 1; p.argv[0] = "eboot.bin"; for (auto& m : m_modules) { if (!m->IsSharedLib()) { #ifdef ARCH_X86_64 ExecuteGuest(RunMainEntry, m->GetEntryAddress(), &p, ProgramExitFunc); #else UNIMPLEMENTED_MSG( "Missing guest entrypoint implementation for target CPU architecture."); #endif } } SetTcbBase(nullptr); } s32 Linker::LoadModule(const std::filesystem::path& elf_name, bool is_dynamic) { std::scoped_lock lk{mutex}; if (!std::filesystem::exists(elf_name)) { LOG_ERROR(Core_Linker, "Provided file {} does not exist", elf_name.string()); return -1; } auto module = std::make_unique<Module>(memory, elf_name, max_tls_index); if (!module->IsValid()) { LOG_ERROR(Core_Linker, "Provided file {} is not valid ELF file", elf_name.string()); return -1; } num_static_modules += !is_dynamic; m_modules.emplace_back(std::move(module)); return m_modules.size() - 1; } Module* Linker::FindByAddress(VAddr address) { for (auto& module : m_modules) { const VAddr base = module->GetBaseAddress(); if (address >= base && address < base + module->aligned_base_size) { return module.get(); } } return nullptr; } void Linker::Relocate(Module* module) { module->ForEachRelocation([&](elf_relocation* rel, u32 i, bool isJmpRel) { const u32 bit_idx = (isJmpRel ? module->dynamic_info.relocation_table_size / sizeof(elf_relocation) : 0) + i; if (module->TestRelaBit(bit_idx)) { return; } auto type = rel->GetType(); auto symbol = rel->GetSymbol(); auto addend = rel->rel_addend; auto* symbol_table = module->dynamic_info.symbol_table; auto* namesTlb = module->dynamic_info.str_table; const VAddr rel_base_virtual_addr = module->GetBaseAddress(); const VAddr rel_virtual_addr = rel_base_virtual_addr + rel->rel_offset; bool rel_is_resolved = false; u64 rel_value = 0; Loader::SymbolType rel_sym_type = Loader::SymbolType::Unknown; std::string rel_name; switch (type) { case R_X86_64_RELATIVE: rel_value = rel_base_virtual_addr + addend; rel_is_resolved = true; module->SetRelaBit(bit_idx); break; case R_X86_64_DTPMOD64: rel_value = static_cast<u64>(module->tls.modid); rel_is_resolved = true; rel_sym_type = Loader::SymbolType::Tls; module->SetRelaBit(bit_idx); break; case R_X86_64_GLOB_DAT: case R_X86_64_JUMP_SLOT: addend = 0; case R_X86_64_64: { auto sym = symbol_table[symbol]; auto sym_bind = sym.GetBind(); auto sym_type = sym.GetType(); auto sym_visibility = sym.GetVisibility(); u64 symbol_virtual_addr = 0; Loader::SymbolRecord symrec{}; switch (sym_type) { case STT_FUN: rel_sym_type = Loader::SymbolType::Function; break; case STT_OBJECT: rel_sym_type = Loader::SymbolType::Object; break; case STT_NOTYPE: rel_sym_type = Loader::SymbolType::NoType; break; default: ASSERT_MSG(0, "unknown symbol type {}", sym_type); } if (sym_visibility != 0) { LOG_INFO(Core_Linker, "symbol visibility !=0"); } switch (sym_bind) { case STB_LOCAL: symbol_virtual_addr = rel_base_virtual_addr + sym.st_value; module->SetRelaBit(bit_idx); break; case STB_GLOBAL: case STB_WEAK: { rel_name = namesTlb + sym.st_name; if (Resolve(rel_name, rel_sym_type, module, &symrec)) { // Only set the rela bit if the symbol was actually resolved and not stubbed. module->SetRelaBit(bit_idx); } symbol_virtual_addr = symrec.virtual_address; break; } default: ASSERT_MSG(0, "unknown bind type {}", sym_bind); } rel_is_resolved = (symbol_virtual_addr != 0); rel_value = (rel_is_resolved ? symbol_virtual_addr + addend : 0); rel_name = symrec.name; break; } default: LOG_INFO(Core_Linker, "UNK type {:#010x} rel symbol : {:#010x}", type, symbol); } if (rel_is_resolved) { VirtualMemory::memory_patch(rel_virtual_addr, rel_value); } else { LOG_INFO(Core_Linker, "function not patched! {}", rel_name); } }); } const Module* Linker::FindExportedModule(const ModuleInfo& module, const LibraryInfo& library) { const auto it = std::ranges::find_if(m_modules, [&](const auto& m) { return std::ranges::contains(m->GetExportLibs(), library) && std::ranges::contains(m->GetExportModules(), module); }); return it == m_modules.end() ? nullptr : it->get(); } bool Linker::Resolve(const std::string& name, Loader::SymbolType sym_type, Module* m, Loader::SymbolRecord* return_info) { const auto ids = Common::SplitString(name, '#'); if (ids.size() != 3) { return_info->virtual_address = 0; return_info->name = name; LOG_ERROR(Core_Linker, "Not Resolved {}", name); return false; } const LibraryInfo* library = m->FindLibrary(ids[1]); const ModuleInfo* module = m->FindModule(ids[2]); ASSERT_MSG(library && module, "Unable to find library and module"); Loader::SymbolResolver sr{}; sr.name = ids.at(0); sr.library = library->name; sr.library_version = library->version; sr.module = module->name; sr.module_version_major = module->version_major; sr.module_version_minor = module->version_minor; sr.type = sym_type; const auto* record = m_hle_symbols.FindSymbol(sr); if (!record) { // Check if it an export function const auto* p = FindExportedModule(*module, *library); if (p && p->export_sym.GetSize() > 0) { record = p->export_sym.FindSymbol(sr); } } if (record) { *return_info = *record; return true; } const auto aeronid = AeroLib::FindByNid(sr.name.c_str()); if (aeronid) { return_info->name = aeronid->name; return_info->virtual_address = AeroLib::GetStub(aeronid->nid); } else { return_info->virtual_address = AeroLib::GetStub(sr.name.c_str()); return_info->name = "Unknown !!!"; } LOG_ERROR(Core_Linker, "Linker: Stub resolved {} as {} (lib: {}, mod: {})", sr.name, return_info->name, library->name, module->name); return false; } void* Linker::TlsGetAddr(u64 module_index, u64 offset) { std::scoped_lock lk{mutex}; DtvEntry* dtv_table = GetTcbBase()->tcb_dtv; if (dtv_table[0].counter != dtv_generation_counter) { // Generation counter changed, a dynamic module was either loaded or unloaded. const u32 old_num_dtvs = dtv_table[1].counter; ASSERT_MSG(max_tls_index > old_num_dtvs, "Module unloading unsupported"); // Module was loaded, increase DTV table size. DtvEntry* new_dtv_table = new DtvEntry[max_tls_index + 2]; std::memcpy(new_dtv_table + 2, dtv_table + 2, old_num_dtvs * sizeof(DtvEntry)); new_dtv_table[0].counter = dtv_generation_counter; new_dtv_table[1].counter = max_tls_index; delete[] dtv_table; // Update TCB pointer. GetTcbBase()->tcb_dtv = new_dtv_table; dtv_table = new_dtv_table; } u8* addr = dtv_table[module_index + 1].pointer; if (!addr) { // Module was just loaded by above code. Allocate TLS block for it. Module* module = m_modules[module_index - 1].get(); const u32 init_image_size = module->tls.init_image_size; // TODO: Determine if Windows will crash from this u8* dest = reinterpret_cast<u8*>(ExecuteGuest(heap_api->heap_malloc, module->tls.image_size)); const u8* src = reinterpret_cast<const u8*>(module->tls.image_virtual_addr); std::memcpy(dest, src, init_image_size); std::memset(dest + init_image_size, 0, module->tls.image_size - init_image_size); dtv_table[module_index + 1].pointer = dest; addr = dest; } return addr + offset; } thread_local std::once_flag init_tls_flag; void Linker::EnsureThreadInitialized(bool is_primary) const { std::call_once(init_tls_flag, [this, is_primary] { #ifdef ARCH_X86_64 InitializeThreadPatchStack(); #endif InitTlsForThread(is_primary); }); } void Linker::InitTlsForThread(bool is_primary) const { static constexpr size_t TcbSize = 0x40; static constexpr size_t TlsAllocAlign = 0x20; const size_t total_tls_size = Common::AlignUp(static_tls_size, TlsAllocAlign) + TcbSize; // If sceKernelMapNamedFlexibleMemory is being called from libkernel and addr = 0 // it automatically places mappings in system reserved area instead of managed. static constexpr VAddr KernelAllocBase = 0x880000000ULL; // The kernel module has a few different paths for TLS allocation. // For SDK < 1.7 it allocates both main and secondary thread blocks using libc mspace/malloc. // In games compiled with newer SDK, the main thread gets mapped from flexible memory, // with addr = 0, so system managed area. Here we will only implement the latter. void* addr_out{reinterpret_cast<void*>(KernelAllocBase)}; if (is_primary) { const size_t tls_aligned = Common::AlignUp(total_tls_size, 16_KB); const int ret = Libraries::Kernel::sceKernelMapNamedFlexibleMemory( &addr_out, tls_aligned, 3, 0, "SceKernelPrimaryTcbTls"); ASSERT_MSG(ret == 0, "Unable to allocate TLS+TCB for the primary thread"); } else { if (heap_api) { #ifndef WIN32 addr_out = ExecuteGuestWithoutTls(heap_api->heap_malloc, total_tls_size); } else { addr_out = std::malloc(total_tls_size); #else // TODO: Windows tls malloc replacement, refer to rtld_tls_block_malloc LOG_ERROR(Core_Linker, "TLS user malloc called, using std::malloc"); addr_out = std::malloc(total_tls_size); if (!addr_out) { auto pth_id = pthread_self(); auto handle = pthread_gethandle(pth_id); ASSERT_MSG(addr_out, "Cannot allocate TLS block defined for handle=%x, index=%d size=%d", handle, pth_id, total_tls_size); } #endif } } // Initialize allocated memory and allocate DTV table. const u32 num_dtvs = max_tls_index; std::memset(addr_out, 0, total_tls_size); DtvEntry* dtv_table = new DtvEntry[num_dtvs + 2]; // Initialize thread control block u8* addr = reinterpret_cast<u8*>(addr_out); Tcb* tcb = reinterpret_cast<Tcb*>(addr + static_tls_size); tcb->tcb_self = tcb; tcb->tcb_dtv = dtv_table; // Dtv[0] is the generation counter. libkernel puts their number into dtv[1] (why?) dtv_table[0].counter = dtv_generation_counter; dtv_table[1].counter = num_dtvs; // Copy init images to TLS thread blocks and map them to DTV slots. for (u32 i = 0; i < num_static_modules; i++) { auto* module = m_modules[i].get(); if (module->tls.image_size == 0) { continue; } u8* dest = reinterpret_cast<u8*>(addr + static_tls_size - module->tls.offset); const u8* src = reinterpret_cast<const u8*>(module->tls.image_virtual_addr); std::memcpy(dest, src, module->tls.init_image_size); tcb->tcb_dtv[module->tls.modid + 1].pointer = dest; } // Set pointer to FS base SetTcbBase(tcb); } void Linker::DebugDump() { const auto& log_dir = Common::FS::GetUserPath(Common::FS::PathType::LogDir); const std::filesystem::path debug(log_dir / "debugdump"); std::filesystem::create_directory(debug); for (const auto& m : m_modules) { // TODO make a folder with game id for being more unique? const std::filesystem::path filepath(debug / m.get()->file.stem()); std::filesystem::create_directory(filepath); m.get()->import_sym.DebugDump(filepath / "imports.txt"); m.get()->export_sym.DebugDump(filepath / "exports.txt"); if (m.get()->elf.IsSelfFile()) { m.get()->elf.SelfHeaderDebugDump(filepath / "selfHeader.txt"); m.get()->elf.SelfSegHeaderDebugDump(filepath / "selfSegHeaders.txt"); } m.get()->elf.ElfHeaderDebugDump(filepath / "elfHeader.txt"); m.get()->elf.PHeaderDebugDump(filepath / "elfPHeaders.txt"); } } } // namespace Core
16,498
C++
.cpp
389
33.953728
99
0.606565
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,541
signals.cpp
shadps4-emu_shadPS4/src/core/signals.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/arch.h" #include "common/assert.h" #include "common/decoder.h" #include "common/signal_context.h" #include "core/signals.h" #ifdef _WIN32 #include <windows.h> #else #include <csignal> #ifdef ARCH_X86_64 #include <Zydis/Formatter.h> #endif #endif namespace Core { #if defined(_WIN32) static LONG WINAPI SignalHandler(EXCEPTION_POINTERS* pExp) noexcept { const auto* signals = Signals::Instance(); bool handled = false; switch (pExp->ExceptionRecord->ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: handled = signals->DispatchAccessViolation( pExp, reinterpret_cast<void*>(pExp->ExceptionRecord->ExceptionInformation[1])); break; case EXCEPTION_ILLEGAL_INSTRUCTION: handled = signals->DispatchIllegalInstruction(pExp); break; default: break; } return handled ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; } #else static std::string DisassembleInstruction(void* code_address) { char buffer[256] = "<unable to decode>"; #ifdef ARCH_X86_64 ZydisDecodedInstruction instruction; ZydisDecodedOperand operands[ZYDIS_MAX_OPERAND_COUNT]; const auto status = Common::Decoder::Instance()->decodeInstruction(instruction, operands, code_address); if (ZYAN_SUCCESS(status)) { ZydisFormatter formatter; ZydisFormatterInit(&formatter, ZYDIS_FORMATTER_STYLE_INTEL); ZydisFormatterFormatInstruction(&formatter, &instruction, operands, instruction.operand_count_visible, buffer, sizeof(buffer), reinterpret_cast<u64>(code_address), ZYAN_NULL); } #endif return buffer; } static void SignalHandler(int sig, siginfo_t* info, void* raw_context) { const auto* signals = Signals::Instance(); auto* code_address = Common::GetRip(raw_context); switch (sig) { case SIGSEGV: case SIGBUS: { const bool is_write = Common::IsWriteError(raw_context); if (!signals->DispatchAccessViolation(raw_context, info->si_addr)) { UNREACHABLE_MSG("Unhandled access violation at code address {}: {} address {}", fmt::ptr(code_address), is_write ? "Write to" : "Read from", fmt::ptr(info->si_addr)); } break; } case SIGILL: if (!signals->DispatchIllegalInstruction(raw_context)) { UNREACHABLE_MSG("Unhandled illegal instruction at code address {}: {}", fmt::ptr(code_address), DisassembleInstruction(code_address)); } break; case SIGUSR1: { // Sleep thread until signal is received sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, SIGUSR1); sigwait(&sigset, &sig); } break; default: break; } } #endif SignalDispatch::SignalDispatch() { #if defined(_WIN32) ASSERT_MSG(handle = AddVectoredExceptionHandler(0, SignalHandler), "Failed to register exception handler."); #else struct sigaction action {}; action.sa_sigaction = SignalHandler; action.sa_flags = SA_SIGINFO | SA_ONSTACK; sigemptyset(&action.sa_mask); ASSERT_MSG(sigaction(SIGSEGV, &action, nullptr) == 0 && sigaction(SIGBUS, &action, nullptr) == 0, "Failed to register access violation signal handler."); ASSERT_MSG(sigaction(SIGILL, &action, nullptr) == 0, "Failed to register illegal instruction signal handler."); ASSERT_MSG(sigaction(SIGUSR1, &action, nullptr) == 0, "Failed to register sleep signal handler."); #endif } SignalDispatch::~SignalDispatch() { #if defined(_WIN32) ASSERT_MSG(RemoveVectoredExceptionHandler(handle), "Failed to remove exception handler."); #else struct sigaction action {}; action.sa_handler = SIG_DFL; action.sa_flags = 0; sigemptyset(&action.sa_mask); ASSERT_MSG(sigaction(SIGSEGV, &action, nullptr) == 0 && sigaction(SIGBUS, &action, nullptr) == 0, "Failed to remove access violation signal handler."); ASSERT_MSG(sigaction(SIGILL, &action, nullptr) == 0, "Failed to remove illegal instruction signal handler."); #endif } bool SignalDispatch::DispatchAccessViolation(void* context, void* fault_address) const { for (const auto& [handler, _] : access_violation_handlers) { if (handler(context, fault_address)) { return true; } } return false; } bool SignalDispatch::DispatchIllegalInstruction(void* context) const { for (const auto& [handler, _] : illegal_instruction_handlers) { if (handler(context)) { return true; } } return false; } } // namespace Core
4,916
C++
.cpp
132
30.477273
98
0.661348
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,542
tls.cpp
shadps4-emu_shadPS4/src/core/tls.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <mutex> #include "common/arch.h" #include "common/assert.h" #include "common/types.h" #include "core/tls.h" #ifdef _WIN32 #include <windows.h> #elif defined(__APPLE__) && defined(ARCH_X86_64) #include <architecture/i386/table.h> #include <boost/icl/interval_set.hpp> #include <i386/user_ldt.h> #include <sys/mman.h> #elif !defined(ARCH_X86_64) #include <pthread.h> #endif namespace Core { #ifdef _WIN32 // Windows static DWORD slot = 0; static std::once_flag slot_alloc_flag; static void AllocTcbKey() { slot = TlsAlloc(); } u32 GetTcbKey() { std::call_once(slot_alloc_flag, &AllocTcbKey); return slot; } void SetTcbBase(void* image_address) { const BOOL result = TlsSetValue(GetTcbKey(), image_address); ASSERT(result != 0); } Tcb* GetTcbBase() { return reinterpret_cast<Tcb*>(TlsGetValue(GetTcbKey())); } #elif defined(__APPLE__) && defined(ARCH_X86_64) // Apple x86_64 // Reserve space in the 32-bit address range for allocating TCB pages. asm(".zerofill TCB_SPACE,TCB_SPACE,__guest_system,0x3FC000"); static constexpr u64 ldt_region_base = 0x4000; static constexpr u64 ldt_region_size = 0x3FC000; static constexpr u16 ldt_block_size = 0x1000; static constexpr u16 ldt_index_base = 8; static constexpr u16 ldt_index_total = (ldt_region_size - ldt_region_base) / ldt_block_size; static boost::icl::interval_set<u16> free_ldts{}; static std::mutex free_ldts_lock; static std::once_flag ldt_region_init_flag; static u16 GetLdtIndex() { sel_t selector; asm volatile("mov %%fs, %0" : "=r"(selector)); return selector.index; } static void InitLdtRegion() { const void* result = mmap(reinterpret_cast<void*>(ldt_region_base), ldt_region_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); ASSERT_MSG(result != MAP_FAILED, "Failed to map memory region for LDT entries."); free_ldts += boost::icl::interval<u16>::right_open(ldt_index_base, ldt_index_base + ldt_index_total); } static void** SetupThreadLdt() { std::call_once(ldt_region_init_flag, InitLdtRegion); // Allocate a new LDT index for the current thread. u16 ldt_index; { std::unique_lock lock{free_ldts_lock}; ASSERT_MSG(!free_ldts.empty(), "Out of LDT space."); ldt_index = first(*free_ldts.begin()); free_ldts -= ldt_index; } const u64 addr = ldt_region_base + (ldt_index - ldt_index_base) * ldt_block_size; // Create an LDT entry for the TCB. const ldt_entry ldt{.data{ .base00 = static_cast<u16>(addr), .base16 = static_cast<u8>(addr >> 16), .base24 = static_cast<u8>(addr >> 24), .limit00 = static_cast<u16>(ldt_block_size - 1), .limit16 = 0, .type = DESC_DATA_WRITE, .dpl = 3, // User accessible .present = 1, // Segment present .stksz = DESC_DATA_32B, .granular = DESC_GRAN_BYTE, }}; int ret = i386_set_ldt(ldt_index, &ldt, 1); ASSERT_MSG(ret == ldt_index, "Failed to set LDT for TLS area: expected {}, but syscall returned {}", ldt_index, ret); // Set the FS segment to the created LDT. const sel_t sel{ .rpl = USER_PRIV, .ti = SEL_LDT, .index = ldt_index, }; asm volatile("mov %0, %%fs" ::"r"(sel)); return reinterpret_cast<void**>(addr); } static void FreeThreadLdt() { std::unique_lock lock{free_ldts_lock}; free_ldts += GetLdtIndex(); } void SetTcbBase(void* image_address) { if (image_address != nullptr) { *SetupThreadLdt() = image_address; } else { FreeThreadLdt(); } } Tcb* GetTcbBase() { Tcb* tcb; asm volatile("mov %%fs:0x0, %0" : "=r"(tcb)); return tcb; } #elif defined(ARCH_X86_64) // Other POSIX x86_64 void SetTcbBase(void* image_address) { asm volatile("wrgsbase %0" ::"r"(image_address) : "memory"); } Tcb* GetTcbBase() { Tcb* tcb; asm volatile("rdgsbase %0" : "=r"(tcb)::"memory"); return tcb; } #else // POSIX non-x86_64 // Just sets up a simple thread-local variable to store it, then instruction translation can point // code to it. static pthread_key_t slot = 0; static std::once_flag slot_alloc_flag; static void AllocTcbKey() { ASSERT(pthread_key_create(&slot, nullptr) == 0); } pthread_key_t GetTcbKey() { std::call_once(slot_alloc_flag, &AllocTcbKey); return slot; } void SetTcbBase(void* image_address) { ASSERT(pthread_setspecific(GetTcbKey(), image_address) == 0); } Tcb* GetTcbBase() { return static_cast<Tcb*>(pthread_getspecific(GetTcbKey())); } #endif } // namespace Core
4,749
C++
.cpp
145
28.786207
98
0.666156
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,543
memory.cpp
shadps4-emu_shadPS4/src/core/memory.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/alignment.h" #include "common/assert.h" #include "common/config.h" #include "common/debug.h" #include "core/libraries/error_codes.h" #include "core/libraries/kernel/memory_management.h" #include "core/memory.h" #include "video_core/renderer_vulkan/vk_instance.h" #include "video_core/renderer_vulkan/vk_rasterizer.h" namespace Core { constexpr u64 SCE_DEFAULT_FLEXIBLE_MEMORY_SIZE = 448_MB; MemoryManager::MemoryManager() { // Set up the direct and flexible memory regions. SetupMemoryRegions(SCE_DEFAULT_FLEXIBLE_MEMORY_SIZE); // Insert a virtual memory area that covers the entire area we manage. const VAddr system_managed_base = impl.SystemManagedVirtualBase(); const size_t system_managed_size = impl.SystemManagedVirtualSize(); const VAddr system_reserved_base = impl.SystemReservedVirtualBase(); const size_t system_reserved_size = impl.SystemReservedVirtualSize(); const VAddr user_base = impl.UserVirtualBase(); const size_t user_size = impl.UserVirtualSize(); vma_map.emplace(system_managed_base, VirtualMemoryArea{system_managed_base, system_managed_size}); vma_map.emplace(system_reserved_base, VirtualMemoryArea{system_reserved_base, system_reserved_size}); vma_map.emplace(user_base, VirtualMemoryArea{user_base, user_size}); // Log initialization. LOG_INFO(Kernel_Vmm, "Usable memory address space: {}_GB", (system_managed_size + system_reserved_size + user_size) >> 30); } MemoryManager::~MemoryManager() = default; void MemoryManager::SetupMemoryRegions(u64 flexible_size) { const auto total_size = Config::isNeoMode() ? SCE_KERNEL_MAIN_DMEM_SIZE_PRO : SCE_KERNEL_MAIN_DMEM_SIZE; total_flexible_size = flexible_size; total_direct_size = total_size - flexible_size; // Insert an area that covers direct memory physical block. // Note that this should never be called after direct memory allocations have been made. dmem_map.clear(); dmem_map.emplace(0, DirectMemoryArea{0, total_direct_size}); LOG_INFO(Kernel_Vmm, "Configured memory regions: flexible size = {:#x}, direct size = {:#x}", total_flexible_size, total_direct_size); } bool MemoryManager::TryWriteBacking(void* address, const void* data, u32 num_bytes) { const VAddr virtual_addr = std::bit_cast<VAddr>(address); const auto& vma = FindVMA(virtual_addr)->second; if (vma.type != VMAType::Direct) { return false; } u8* backing = impl.BackingBase() + vma.phys_base + (virtual_addr - vma.base); memcpy(backing, data, num_bytes); return true; } PAddr MemoryManager::PoolExpand(PAddr search_start, PAddr search_end, size_t size, u64 alignment) { std::scoped_lock lk{mutex}; auto dmem_area = FindDmemArea(search_start); const auto is_suitable = [&] { const auto aligned_base = alignment > 0 ? Common::AlignUp(dmem_area->second.base, alignment) : dmem_area->second.base; const auto alignment_size = aligned_base - dmem_area->second.base; const auto remaining_size = dmem_area->second.size >= alignment_size ? dmem_area->second.size - alignment_size : 0; return dmem_area->second.is_free && remaining_size >= size; }; while (!is_suitable() && dmem_area->second.GetEnd() <= search_end) { dmem_area++; } ASSERT_MSG(is_suitable(), "Unable to find free direct memory area: size = {:#x}", size); // Align free position PAddr free_addr = dmem_area->second.base; free_addr = alignment > 0 ? Common::AlignUp(free_addr, alignment) : free_addr; // Add the allocated region to the list and commit its pages. auto& area = CarveDmemArea(free_addr, size)->second; area.is_free = false; area.is_pooled = true; return free_addr; } PAddr MemoryManager::Allocate(PAddr search_start, PAddr search_end, size_t size, u64 alignment, int memory_type) { std::scoped_lock lk{mutex}; auto dmem_area = FindDmemArea(search_start); const auto is_suitable = [&] { const auto aligned_base = alignment > 0 ? Common::AlignUp(dmem_area->second.base, alignment) : dmem_area->second.base; const auto alignment_size = aligned_base - dmem_area->second.base; const auto remaining_size = dmem_area->second.size >= alignment_size ? dmem_area->second.size - alignment_size : 0; return dmem_area->second.is_free && remaining_size >= size; }; while (!is_suitable() && dmem_area->second.GetEnd() <= search_end) { ++dmem_area; } ASSERT_MSG(is_suitable(), "Unable to find free direct memory area: size = {:#x}", size); // Align free position PAddr free_addr = dmem_area->second.base; free_addr = alignment > 0 ? Common::AlignUp(free_addr, alignment) : free_addr; // Add the allocated region to the list and commit its pages. auto& area = CarveDmemArea(free_addr, size)->second; area.memory_type = memory_type; area.is_free = false; return free_addr; } void MemoryManager::Free(PAddr phys_addr, size_t size) { std::scoped_lock lk{mutex}; auto dmem_area = CarveDmemArea(phys_addr, size); ASSERT(dmem_area != dmem_map.end() && dmem_area->second.size >= size); // Release any dmem mappings that reference this physical block. std::vector<std::pair<VAddr, u64>> remove_list; for (const auto& [addr, mapping] : vma_map) { if (mapping.type != VMAType::Direct) { continue; } if (mapping.phys_base <= phys_addr && phys_addr < mapping.phys_base + mapping.size) { auto vma_segment_start_addr = phys_addr - mapping.phys_base + addr; LOG_INFO(Kernel_Vmm, "Unmaping direct mapping {:#x} with size {:#x}", vma_segment_start_addr, size); // Unmaping might erase from vma_map. We can't do it here. remove_list.emplace_back(vma_segment_start_addr, size); } } for (const auto& [addr, size] : remove_list) { UnmapMemoryImpl(addr, size); } // Mark region as free and attempt to coalesce it with neighbours. auto& area = dmem_area->second; area.is_free = true; area.memory_type = 0; MergeAdjacent(dmem_map, dmem_area); } int MemoryManager::PoolReserve(void** out_addr, VAddr virtual_addr, size_t size, MemoryMapFlags flags, u64 alignment) { std::scoped_lock lk{mutex}; virtual_addr = (virtual_addr == 0) ? impl.SystemManagedVirtualBase() : virtual_addr; alignment = alignment > 0 ? alignment : 2_MB; VAddr mapped_addr = alignment > 0 ? Common::AlignUp(virtual_addr, alignment) : virtual_addr; // Fixed mapping means the virtual address must exactly match the provided one. if (True(flags & MemoryMapFlags::Fixed)) { const auto& vma = FindVMA(mapped_addr)->second; // If the VMA is mapped, unmap the region first. if (vma.IsMapped()) { UnmapMemoryImpl(mapped_addr, size); } const size_t remaining_size = vma.base + vma.size - mapped_addr; ASSERT_MSG(vma.type == VMAType::Free && remaining_size >= size); } // Find the first free area starting with provided virtual address. if (False(flags & MemoryMapFlags::Fixed)) { mapped_addr = SearchFree(mapped_addr, size, alignment); } // Add virtual memory area const auto new_vma_handle = CarveVMA(mapped_addr, size); auto& new_vma = new_vma_handle->second; new_vma.disallow_merge = True(flags & MemoryMapFlags::NoCoalesce); new_vma.prot = MemoryProt::NoAccess; new_vma.name = ""; new_vma.type = VMAType::PoolReserved; MergeAdjacent(vma_map, new_vma_handle); *out_addr = std::bit_cast<void*>(mapped_addr); return ORBIS_OK; } int MemoryManager::Reserve(void** out_addr, VAddr virtual_addr, size_t size, MemoryMapFlags flags, u64 alignment) { std::scoped_lock lk{mutex}; virtual_addr = (virtual_addr == 0) ? impl.SystemManagedVirtualBase() : virtual_addr; alignment = alignment > 0 ? alignment : 16_KB; VAddr mapped_addr = alignment > 0 ? Common::AlignUp(virtual_addr, alignment) : virtual_addr; // Fixed mapping means the virtual address must exactly match the provided one. if (True(flags & MemoryMapFlags::Fixed)) { const auto& vma = FindVMA(mapped_addr)->second; // If the VMA is mapped, unmap the region first. if (vma.IsMapped()) { UnmapMemoryImpl(mapped_addr, size); } const size_t remaining_size = vma.base + vma.size - mapped_addr; ASSERT_MSG(vma.type == VMAType::Free && remaining_size >= size); } // Find the first free area starting with provided virtual address. if (False(flags & MemoryMapFlags::Fixed)) { mapped_addr = SearchFree(mapped_addr, size, alignment); } // Add virtual memory area const auto new_vma_handle = CarveVMA(mapped_addr, size); auto& new_vma = new_vma_handle->second; new_vma.disallow_merge = True(flags & MemoryMapFlags::NoCoalesce); new_vma.prot = MemoryProt::NoAccess; new_vma.name = ""; new_vma.type = VMAType::Reserved; MergeAdjacent(vma_map, new_vma_handle); *out_addr = std::bit_cast<void*>(mapped_addr); return ORBIS_OK; } int MemoryManager::PoolCommit(VAddr virtual_addr, size_t size, MemoryProt prot) { std::scoped_lock lk{mutex}; const u64 alignment = 64_KB; // When virtual addr is zero, force it to virtual_base. The guest cannot pass Fixed // flag so we will take the branch that searches for free (or reserved) mappings. virtual_addr = (virtual_addr == 0) ? impl.SystemManagedVirtualBase() : virtual_addr; VAddr mapped_addr = Common::AlignUp(virtual_addr, alignment); // This should return SCE_KERNEL_ERROR_ENOMEM but shouldn't normally happen. const auto& vma = FindVMA(mapped_addr)->second; const size_t remaining_size = vma.base + vma.size - mapped_addr; ASSERT_MSG(!vma.IsMapped() && remaining_size >= size); // Perform the mapping. void* out_addr = impl.Map(mapped_addr, size, alignment, -1, false); TRACK_ALLOC(out_addr, size, "VMEM"); auto& new_vma = CarveVMA(mapped_addr, size)->second; new_vma.disallow_merge = false; new_vma.prot = prot; new_vma.name = ""; new_vma.type = Core::VMAType::Pooled; new_vma.is_exec = false; new_vma.phys_base = 0; rasterizer->MapMemory(mapped_addr, size); return ORBIS_OK; } int MemoryManager::MapMemory(void** out_addr, VAddr virtual_addr, size_t size, MemoryProt prot, MemoryMapFlags flags, VMAType type, std::string_view name, bool is_exec, PAddr phys_addr, u64 alignment) { std::scoped_lock lk{mutex}; // Certain games perform flexible mappings on loop to determine // the available flexible memory size. Questionable but we need to handle this. if (type == VMAType::Flexible && flexible_usage + size > total_flexible_size) { return SCE_KERNEL_ERROR_ENOMEM; } // When virtual addr is zero, force it to virtual_base. The guest cannot pass Fixed // flag so we will take the branch that searches for free (or reserved) mappings. virtual_addr = (virtual_addr == 0) ? impl.SystemManagedVirtualBase() : virtual_addr; alignment = alignment > 0 ? alignment : 16_KB; VAddr mapped_addr = alignment > 0 ? Common::AlignUp(virtual_addr, alignment) : virtual_addr; // Fixed mapping means the virtual address must exactly match the provided one. if (True(flags & MemoryMapFlags::Fixed)) { // This should return SCE_KERNEL_ERROR_ENOMEM but shouldn't normally happen. const auto& vma = FindVMA(mapped_addr)->second; const size_t remaining_size = vma.base + vma.size - mapped_addr; ASSERT_MSG(!vma.IsMapped() && remaining_size >= size); } // Find the first free area starting with provided virtual address. if (False(flags & MemoryMapFlags::Fixed)) { mapped_addr = SearchFree(mapped_addr, size, alignment); } // Perform the mapping. *out_addr = impl.Map(mapped_addr, size, alignment, phys_addr, is_exec); TRACK_ALLOC(*out_addr, size, "VMEM"); auto& new_vma = CarveVMA(mapped_addr, size)->second; new_vma.disallow_merge = True(flags & MemoryMapFlags::NoCoalesce); new_vma.prot = prot; new_vma.name = name; new_vma.type = type; new_vma.is_exec = is_exec; if (type == VMAType::Direct) { new_vma.phys_base = phys_addr; rasterizer->MapMemory(mapped_addr, size); } if (type == VMAType::Flexible) { flexible_usage += size; } return ORBIS_OK; } int MemoryManager::MapFile(void** out_addr, VAddr virtual_addr, size_t size, MemoryProt prot, MemoryMapFlags flags, uintptr_t fd, size_t offset) { VAddr mapped_addr = (virtual_addr == 0) ? impl.SystemManagedVirtualBase() : virtual_addr; const size_t size_aligned = Common::AlignUp(size, 16_KB); // Find first free area to map the file. if (False(flags & MemoryMapFlags::Fixed)) { mapped_addr = SearchFree(mapped_addr, size_aligned, 1); } if (True(flags & MemoryMapFlags::Fixed)) { const auto& vma = FindVMA(virtual_addr)->second; const size_t remaining_size = vma.base + vma.size - virtual_addr; ASSERT_MSG(!vma.IsMapped() && remaining_size >= size); } // Map the file. impl.MapFile(mapped_addr, size, offset, std::bit_cast<u32>(prot), fd); // Add virtual memory area auto& new_vma = CarveVMA(mapped_addr, size_aligned)->second; new_vma.disallow_merge = True(flags & MemoryMapFlags::NoCoalesce); new_vma.prot = prot; new_vma.name = "File"; new_vma.fd = fd; new_vma.type = VMAType::File; *out_addr = std::bit_cast<void*>(mapped_addr); return ORBIS_OK; } void MemoryManager::PoolDecommit(VAddr virtual_addr, size_t size) { std::scoped_lock lk{mutex}; const auto it = FindVMA(virtual_addr); const auto& vma_base = it->second; ASSERT_MSG(vma_base.Contains(virtual_addr, size), "Existing mapping does not contain requested unmap range"); const auto vma_base_addr = vma_base.base; const auto vma_base_size = vma_base.size; const auto phys_base = vma_base.phys_base; const bool is_exec = vma_base.is_exec; const auto start_in_vma = virtual_addr - vma_base_addr; const auto type = vma_base.type; rasterizer->UnmapMemory(virtual_addr, size); // Mark region as free and attempt to coalesce it with neighbours. const auto new_it = CarveVMA(virtual_addr, size); auto& vma = new_it->second; vma.type = VMAType::PoolReserved; vma.prot = MemoryProt::NoAccess; vma.phys_base = 0; vma.disallow_merge = false; vma.name = ""; MergeAdjacent(vma_map, new_it); // Unmap the memory region. impl.Unmap(vma_base_addr, vma_base_size, start_in_vma, start_in_vma + size, phys_base, is_exec, false, false); TRACK_FREE(virtual_addr, "VMEM"); } void MemoryManager::UnmapMemory(VAddr virtual_addr, size_t size) { std::scoped_lock lk{mutex}; UnmapMemoryImpl(virtual_addr, size); } void MemoryManager::UnmapMemoryImpl(VAddr virtual_addr, size_t size) { const auto it = FindVMA(virtual_addr); const auto& vma_base = it->second; ASSERT_MSG(vma_base.Contains(virtual_addr, size), "Existing mapping does not contain requested unmap range"); const auto vma_base_addr = vma_base.base; const auto vma_base_size = vma_base.size; const auto phys_base = vma_base.phys_base; const bool is_exec = vma_base.is_exec; const auto start_in_vma = virtual_addr - vma_base_addr; const auto type = vma_base.type; const bool has_backing = type == VMAType::Direct || type == VMAType::File; if (type == VMAType::Direct) { rasterizer->UnmapMemory(virtual_addr, size); } if (type == VMAType::Flexible) { flexible_usage -= size; } // Mark region as free and attempt to coalesce it with neighbours. const auto new_it = CarveVMA(virtual_addr, size); auto& vma = new_it->second; vma.type = VMAType::Free; vma.prot = MemoryProt::NoAccess; vma.phys_base = 0; vma.disallow_merge = false; vma.name = ""; MergeAdjacent(vma_map, new_it); bool readonly_file = vma.prot == MemoryProt::CpuRead && type == VMAType::File; // Unmap the memory region. impl.Unmap(vma_base_addr, vma_base_size, start_in_vma, start_in_vma + size, phys_base, is_exec, has_backing, readonly_file); TRACK_FREE(virtual_addr, "VMEM"); } int MemoryManager::QueryProtection(VAddr addr, void** start, void** end, u32* prot) { std::scoped_lock lk{mutex}; const auto it = FindVMA(addr); const auto& vma = it->second; ASSERT_MSG(vma.type != VMAType::Free, "Provided address is not mapped"); if (start != nullptr) { *start = reinterpret_cast<void*>(vma.base); } if (end != nullptr) { *end = reinterpret_cast<void*>(vma.base + vma.size); } if (prot != nullptr) { *prot = static_cast<u32>(vma.prot); } return ORBIS_OK; } int MemoryManager::Protect(VAddr addr, size_t size, MemoryProt prot) { std::scoped_lock lk{mutex}; // Find the virtual memory area that contains the specified address range. auto it = FindVMA(addr); if (it == vma_map.end() || !it->second.Contains(addr, size)) { LOG_ERROR(Core, "Address range not mapped"); return ORBIS_KERNEL_ERROR_EINVAL; } VirtualMemoryArea& vma = it->second; if (vma.type == VMAType::Free) { LOG_ERROR(Core, "Cannot change protection on free memory region"); return ORBIS_KERNEL_ERROR_EINVAL; } // Validate protection flags constexpr static MemoryProt valid_flags = MemoryProt::NoAccess | MemoryProt::CpuRead | MemoryProt::CpuReadWrite | MemoryProt::GpuRead | MemoryProt::GpuWrite | MemoryProt::GpuReadWrite; MemoryProt invalid_flags = prot & ~valid_flags; if (u32(invalid_flags) != 0 && u32(invalid_flags) != u32(MemoryProt::NoAccess)) { LOG_ERROR(Core, "Invalid protection flags: prot = {:#x}, invalid flags = {:#x}", u32(prot), u32(invalid_flags)); return ORBIS_KERNEL_ERROR_EINVAL; } // Change protection vma.prot = prot; // Set permissions Core::MemoryPermission perms{}; if (True(prot & MemoryProt::CpuRead)) { perms |= Core::MemoryPermission::Read; } if (True(prot & MemoryProt::CpuReadWrite)) { perms |= Core::MemoryPermission::ReadWrite; } if (True(prot & MemoryProt::GpuRead)) { perms |= Core::MemoryPermission::Read; } if (True(prot & MemoryProt::GpuWrite)) { perms |= Core::MemoryPermission::Write; } if (True(prot & MemoryProt::GpuReadWrite)) { perms |= Core::MemoryPermission::ReadWrite; } impl.Protect(addr, size, perms); return ORBIS_OK; } int MemoryManager::VirtualQuery(VAddr addr, int flags, ::Libraries::Kernel::OrbisVirtualQueryInfo* info) { std::scoped_lock lk{mutex}; auto it = FindVMA(addr); if (it->second.type == VMAType::Free && flags == 1) { ++it; } if (it->second.type == VMAType::Free) { LOG_WARNING(Kernel_Vmm, "VirtualQuery on free memory region"); return ORBIS_KERNEL_ERROR_EACCES; } const auto& vma = it->second; info->start = vma.base; info->end = vma.base + vma.size; info->offset = vma.phys_base; info->protection = static_cast<s32>(vma.prot); info->is_flexible.Assign(vma.type == VMAType::Flexible); info->is_direct.Assign(vma.type == VMAType::Direct); info->is_stack.Assign(vma.type == VMAType::Stack); info->is_pooled.Assign(vma.type == VMAType::Pooled); info->is_committed.Assign(vma.type != VMAType::Free && vma.type != VMAType::Reserved && vma.type != VMAType::PoolReserved); vma.name.copy(info->name.data(), std::min(info->name.size(), vma.name.size())); if (vma.type == VMAType::Direct) { const auto dmem_it = FindDmemArea(vma.phys_base); ASSERT(dmem_it != dmem_map.end()); info->memory_type = dmem_it->second.memory_type; } else { info->memory_type = ::Libraries::Kernel::SCE_KERNEL_WB_ONION; } return ORBIS_OK; } int MemoryManager::DirectMemoryQuery(PAddr addr, bool find_next, ::Libraries::Kernel::OrbisQueryInfo* out_info) { std::scoped_lock lk{mutex}; auto dmem_area = FindDmemArea(addr); while (dmem_area != dmem_map.end() && dmem_area->second.is_free && find_next) { dmem_area++; } if (dmem_area == dmem_map.end() || dmem_area->second.is_free) { LOG_ERROR(Core, "Unable to find allocated direct memory region to query!"); return ORBIS_KERNEL_ERROR_EACCES; } const auto& area = dmem_area->second; out_info->start = area.base; out_info->end = area.GetEnd(); out_info->memoryType = area.memory_type; return ORBIS_OK; } int MemoryManager::DirectQueryAvailable(PAddr search_start, PAddr search_end, size_t alignment, PAddr* phys_addr_out, size_t* size_out) { std::scoped_lock lk{mutex}; auto dmem_area = FindDmemArea(search_start); PAddr paddr{}; size_t max_size{}; while (dmem_area != dmem_map.end() && dmem_area->second.GetEnd() <= search_end) { if (!dmem_area->second.is_free) { dmem_area++; continue; } const auto aligned_base = alignment > 0 ? Common::AlignUp(dmem_area->second.base, alignment) : dmem_area->second.base; const auto alignment_size = aligned_base - dmem_area->second.base; const auto remaining_size = dmem_area->second.size >= alignment_size ? dmem_area->second.size - alignment_size : 0; if (remaining_size > max_size) { paddr = aligned_base; max_size = remaining_size; } dmem_area++; } *phys_addr_out = paddr; *size_out = max_size; return ORBIS_OK; } void MemoryManager::NameVirtualRange(VAddr virtual_addr, size_t size, std::string_view name) { auto it = FindVMA(virtual_addr); ASSERT_MSG(it->second.Contains(virtual_addr, size), "Range provided is not fully contained in vma"); it->second.name = name; } VAddr MemoryManager::SearchFree(VAddr virtual_addr, size_t size, u32 alignment) { // If the requested address is below the mapped range, start search from the lowest address auto min_search_address = impl.SystemManagedVirtualBase(); if (virtual_addr < min_search_address) { virtual_addr = min_search_address; } auto it = FindVMA(virtual_addr); ASSERT_MSG(it != vma_map.end(), "Specified mapping address was not found!"); // If the VMA is free and contains the requested mapping we are done. if (it->second.IsFree() && it->second.Contains(virtual_addr, size)) { return virtual_addr; } // Search for the first free VMA that fits our mapping. const auto is_suitable = [&] { if (!it->second.IsFree()) { return false; } const auto& vma = it->second; virtual_addr = Common::AlignUp(vma.base, alignment); // Sometimes the alignment itself might be larger than the VMA. if (virtual_addr > vma.base + vma.size) { return false; } const size_t remaining_size = vma.base + vma.size - virtual_addr; return remaining_size >= size; }; while (!is_suitable()) { ++it; } return virtual_addr; } MemoryManager::VMAHandle MemoryManager::CarveVMA(VAddr virtual_addr, size_t size) { auto vma_handle = FindVMA(virtual_addr); ASSERT_MSG(vma_handle != vma_map.end(), "Virtual address not in vm_map"); const VirtualMemoryArea& vma = vma_handle->second; ASSERT_MSG(vma.base <= virtual_addr, "Adding a mapping to already mapped region"); const VAddr start_in_vma = virtual_addr - vma.base; const VAddr end_in_vma = start_in_vma + size; ASSERT_MSG(end_in_vma <= vma.size, "Mapping cannot fit inside free region"); if (end_in_vma != vma.size) { // Split VMA at the end of the allocated region Split(vma_handle, end_in_vma); } if (start_in_vma != 0) { // Split VMA at the start of the allocated region vma_handle = Split(vma_handle, start_in_vma); } return vma_handle; } MemoryManager::DMemHandle MemoryManager::CarveDmemArea(PAddr addr, size_t size) { auto dmem_handle = FindDmemArea(addr); ASSERT_MSG(dmem_handle != dmem_map.end(), "Physical address not in dmem_map"); const DirectMemoryArea& area = dmem_handle->second; ASSERT_MSG(area.base <= addr, "Adding an allocation to already allocated region"); const PAddr start_in_area = addr - area.base; const PAddr end_in_vma = start_in_area + size; ASSERT_MSG(end_in_vma <= area.size, "Mapping cannot fit inside free region: size = {:#x}", size); if (end_in_vma != area.size) { // Split VMA at the end of the allocated region Split(dmem_handle, end_in_vma); } if (start_in_area != 0) { // Split VMA at the start of the allocated region dmem_handle = Split(dmem_handle, start_in_area); } return dmem_handle; } MemoryManager::VMAHandle MemoryManager::Split(VMAHandle vma_handle, size_t offset_in_vma) { auto& old_vma = vma_handle->second; ASSERT(offset_in_vma < old_vma.size && offset_in_vma > 0); auto new_vma = old_vma; old_vma.size = offset_in_vma; new_vma.base += offset_in_vma; new_vma.size -= offset_in_vma; if (new_vma.type == VMAType::Direct) { new_vma.phys_base += offset_in_vma; } return vma_map.emplace_hint(std::next(vma_handle), new_vma.base, new_vma); } MemoryManager::DMemHandle MemoryManager::Split(DMemHandle dmem_handle, size_t offset_in_area) { auto& old_area = dmem_handle->second; ASSERT(offset_in_area < old_area.size && offset_in_area > 0); auto new_area = old_area; old_area.size = offset_in_area; new_area.base += offset_in_area; new_area.size -= offset_in_area; return dmem_map.emplace_hint(std::next(dmem_handle), new_area.base, new_area); }; int MemoryManager::GetDirectMemoryType(PAddr addr, int* directMemoryTypeOut, void** directMemoryStartOut, void** directMemoryEndOut) { std::scoped_lock lk{mutex}; auto dmem_area = FindDmemArea(addr); if (dmem_area == dmem_map.end() || dmem_area->second.is_free) { LOG_ERROR(Core, "Unable to find allocated direct memory region to check type!"); return ORBIS_KERNEL_ERROR_ENOENT; } const auto& area = dmem_area->second; *directMemoryStartOut = reinterpret_cast<void*>(area.base); *directMemoryEndOut = reinterpret_cast<void*>(area.GetEnd()); *directMemoryTypeOut = area.memory_type; return ORBIS_OK; } } // namespace Core
27,527
C++
.cpp
595
39.492437
100
0.654632
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,544
debug_state.cpp
shadps4-emu_shadPS4/src/core/debug_state.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <imgui.h> #include "common/assert.h" #include "common/native_clock.h" #include "common/singleton.h" #include "debug_state.h" #include "devtools/widget/common.h" #include "libraries/kernel/time_management.h" #include "libraries/system/msgdialog.h" #include "video_core/amdgpu/pm4_cmds.h" using namespace DebugStateType; DebugStateImpl& DebugState = *Common::Singleton<DebugStateImpl>::Instance(); static ThreadID ThisThreadID() { #ifdef _WIN32 return GetCurrentThreadId(); #else return pthread_self(); #endif } static void PauseThread(ThreadID id) { #ifdef _WIN32 auto handle = OpenThread(THREAD_SUSPEND_RESUME, FALSE, id); SuspendThread(handle); CloseHandle(handle); #else pthread_kill(id, SIGUSR1); #endif } static void ResumeThread(ThreadID id) { #ifdef _WIN32 auto handle = OpenThread(THREAD_SUSPEND_RESUME, FALSE, id); ResumeThread(handle); CloseHandle(handle); #else pthread_kill(id, SIGUSR1); #endif } void DebugStateImpl::AddCurrentThreadToGuestList() { std::lock_guard lock{guest_threads_mutex}; const ThreadID id = ThisThreadID(); guest_threads.push_back(id); } void DebugStateImpl::RemoveCurrentThreadFromGuestList() { std::lock_guard lock{guest_threads_mutex}; const ThreadID id = ThisThreadID(); std::erase_if(guest_threads, [&](const ThreadID& v) { return v == id; }); } void DebugStateImpl::PauseGuestThreads() { using namespace Libraries::MsgDialog; std::unique_lock lock{guest_threads_mutex}; if (is_guest_threads_paused) { return; } if (ShouldPauseInSubmit()) { waiting_submit_pause = false; should_show_frame_dump = true; } bool self_guest = false; ThreadID self_id = ThisThreadID(); for (const auto& id : guest_threads) { if (id == self_id) { self_guest = true; } else { PauseThread(id); } } pause_time = Libraries::Kernel::Dev::GetClock()->GetUptime(); is_guest_threads_paused = true; lock.unlock(); if (self_guest) { PauseThread(self_id); } } void DebugStateImpl::ResumeGuestThreads() { std::lock_guard lock{guest_threads_mutex}; if (!is_guest_threads_paused) { return; } u64 delta_time = Libraries::Kernel::Dev::GetClock()->GetUptime() - pause_time; Libraries::Kernel::Dev::GetInitialPtc() += delta_time; for (const auto& id : guest_threads) { ResumeThread(id); } is_guest_threads_paused = false; } void DebugStateImpl::RequestFrameDump(s32 count) { ASSERT(!DumpingCurrentFrame()); gnm_frame_dump_request_count = count; frame_dump_list.clear(); frame_dump_list.resize(count); const auto f = gnm_frame_count.load() + 1; for (size_t i = 0; i < count; ++i) { frame_dump_list[i].frame_id = f + i; } waiting_submit_pause = true; } void DebugStateImpl::PushQueueDump(QueueDump dump) { ASSERT(DumpingCurrentFrame()); std::unique_lock lock{frame_dump_list_mutex}; auto& frame = GetFrameDump(); { // Find draw calls auto data = std::span{dump.data}; auto initial_data = data.data(); while (!data.empty()) { const auto* header = reinterpret_cast<const AmdGpu::PM4Type3Header*>(data.data()); const auto type = header->type; if (type == 2) { data = data.subspan(1); } else if (type != 3) { UNREACHABLE(); } const AmdGpu::PM4ItOpcode opcode = header->opcode; if (Core::Devtools::Widget::IsDrawCall(opcode)) { const auto offset = reinterpret_cast<uintptr_t>(header) - reinterpret_cast<uintptr_t>(initial_data); const auto addr = dump.base_addr + offset; waiting_reg_dumps.emplace(addr, &frame); waiting_reg_dumps_dbg.emplace( addr, fmt::format("#{} h({}) queue {} {} {}", frame_dump_list.size() - gnm_frame_dump_request_count, addr, magic_enum::enum_name(dump.type), dump.submit_num, dump.num2)); } data = data.subspan(header->NumWords() + 1); } } frame.queues.push_back(std::move(dump)); } void DebugStateImpl::PushRegsDump(uintptr_t base_addr, uintptr_t header_addr, const AmdGpu::Liverpool::Regs& regs, bool is_compute) { std::scoped_lock lock{frame_dump_list_mutex}; const auto it = waiting_reg_dumps.find(header_addr); if (it == waiting_reg_dumps.end()) { return; } auto& frame = *it->second; waiting_reg_dumps.erase(it); waiting_reg_dumps_dbg.erase(waiting_reg_dumps_dbg.find(header_addr)); auto& dump = frame.regs[header_addr - base_addr]; dump.regs = regs; if (is_compute) { dump.is_compute = true; const auto& cs = dump.regs.cs_program; dump.cs_data = ComputerShaderDump{ .cs_program = cs, .code = std::vector<u32>{cs.Code().begin(), cs.Code().end()}, }; } else { for (int i = 0; i < RegDump::MaxShaderStages; i++) { if (regs.stage_enable.IsStageEnabled(i)) { auto stage = regs.ProgramForStage(i); if (stage->address_lo != 0) { auto code = stage->Code(); dump.stages[i] = ShaderDump{ .user_data = *stage, .code = std::vector<u32>{code.begin(), code.end()}, }; } } } } }
5,741
C++
.cpp
163
27.883436
100
0.609563
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,545
address_space.cpp
shadps4-emu_shadPS4/src/core/address_space.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <boost/icl/separate_interval_set.hpp> #include "common/alignment.h" #include "common/arch.h" #include "common/assert.h" #include "common/error.h" #include "core/address_space.h" #include "core/libraries/kernel/memory_management.h" #include "core/memory.h" #include "libraries/error_codes.h" #ifdef _WIN32 #include <windows.h> #else #include <fcntl.h> #include <sys/mman.h> #endif #if defined(__APPLE__) && defined(ARCH_X86_64) // Reserve space for the system address space using a zerofill section. asm(".zerofill GUEST_SYSTEM,GUEST_SYSTEM,__guest_system,0xFBFC00000"); #endif namespace Core { static constexpr size_t BackingSize = SCE_KERNEL_MAIN_DMEM_SIZE_PRO; #ifdef _WIN32 [[nodiscard]] constexpr u64 ToWindowsProt(Core::MemoryProt prot) { if (True(prot & Core::MemoryProt::CpuReadWrite) || True(prot & Core::MemoryProt::GpuReadWrite)) { return PAGE_READWRITE; } else if (True(prot & Core::MemoryProt::CpuRead) || True(prot & Core::MemoryProt::GpuRead)) { return PAGE_READONLY; } else { return PAGE_NOACCESS; } } struct AddressSpace::Impl { Impl() : process{GetCurrentProcess()} { // Allocate virtual address placeholder for our address space. MEM_ADDRESS_REQUIREMENTS req{}; MEM_EXTENDED_PARAMETER param{}; req.LowestStartingAddress = reinterpret_cast<PVOID>(SYSTEM_MANAGED_MIN); // The ending address must align to page boundary - 1 // https://stackoverflow.com/questions/54223343/virtualalloc2-with-memextendedparameteraddressrequirements-always-produces-error req.HighestEndingAddress = reinterpret_cast<PVOID>(USER_MIN + UserSize - 1); req.Alignment = 0; param.Type = MemExtendedParameterAddressRequirements; param.Pointer = &req; // Typically, lower parts of system managed area is already reserved in windows. // If reservation fails attempt again by reducing the area size a little bit. // System managed is about 31GB in size so also cap the number of times we can reduce it // to a reasonable amount. static constexpr size_t ReductionOnFail = 1_GB; static constexpr size_t MaxReductions = 10; size_t reduction = 0; size_t virtual_size = SystemManagedSize + SystemReservedSize + UserSize; for (u32 i = 0; i < MaxReductions; i++) { virtual_base = static_cast<u8*>(VirtualAlloc2(process, NULL, virtual_size - reduction, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, &param, 1)); if (virtual_base) { break; } reduction += ReductionOnFail; } ASSERT_MSG(virtual_base, "Unable to reserve virtual address space: {}", Common::GetLastErrorMsg()); // Take the reduction off of the system managed area, and leave the others unchanged. system_managed_base = virtual_base; system_managed_size = SystemManagedSize - reduction; system_reserved_base = reinterpret_cast<u8*>(SYSTEM_RESERVED_MIN); system_reserved_size = SystemReservedSize; user_base = reinterpret_cast<u8*>(USER_MIN); user_size = UserSize; LOG_INFO(Kernel_Vmm, "System managed virtual memory region: {} - {}", fmt::ptr(system_managed_base), fmt::ptr(system_managed_base + system_managed_size - 1)); LOG_INFO(Kernel_Vmm, "System reserved virtual memory region: {} - {}", fmt::ptr(system_reserved_base), fmt::ptr(system_reserved_base + system_reserved_size - 1)); LOG_INFO(Kernel_Vmm, "User virtual memory region: {} - {}", fmt::ptr(user_base), fmt::ptr(user_base + user_size - 1)); // Initializer placeholder tracker const uintptr_t system_managed_addr = reinterpret_cast<uintptr_t>(system_managed_base); const uintptr_t system_reserved_addr = reinterpret_cast<uintptr_t>(system_reserved_base); const uintptr_t user_addr = reinterpret_cast<uintptr_t>(user_base); placeholders.insert({system_managed_addr, virtual_size - reduction}); // Allocate backing file that represents the total physical memory. backing_handle = CreateFileMapping2(INVALID_HANDLE_VALUE, nullptr, FILE_MAP_WRITE | FILE_MAP_READ, PAGE_READWRITE, SEC_COMMIT, BackingSize, nullptr, nullptr, 0); ASSERT_MSG(backing_handle, "{}", Common::GetLastErrorMsg()); // Allocate a virtual memory for the backing file map as placeholder backing_base = static_cast<u8*>(VirtualAlloc2(process, nullptr, BackingSize, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0)); // Map backing placeholder. This will commit the pages void* const ret = MapViewOfFile3(backing_handle, process, backing_base, 0, BackingSize, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0); ASSERT_MSG(ret == backing_base, "{}", Common::GetLastErrorMsg()); } ~Impl() { if (virtual_base) { if (!VirtualFree(virtual_base, 0, MEM_RELEASE)) { LOG_CRITICAL(Render, "Failed to free virtual memory"); } } if (backing_base) { if (!UnmapViewOfFile2(process, backing_base, MEM_PRESERVE_PLACEHOLDER)) { LOG_CRITICAL(Render, "Failed to unmap backing memory placeholder"); } if (!VirtualFreeEx(process, backing_base, 0, MEM_RELEASE)) { LOG_CRITICAL(Render, "Failed to free backing memory"); } } if (!CloseHandle(backing_handle)) { LOG_CRITICAL(Render, "Failed to free backing memory file handle"); } } void* Map(VAddr virtual_addr, PAddr phys_addr, size_t size, ULONG prot, uintptr_t fd = 0) { const size_t aligned_size = Common::AlignUp(size, 16_KB); const auto it = placeholders.find(virtual_addr); ASSERT_MSG(it != placeholders.end(), "Cannot map already mapped region"); ASSERT_MSG(virtual_addr >= it->lower() && virtual_addr + aligned_size <= it->upper(), "Map range must be fully contained in a placeholder"); // Windows only allows splitting a placeholder into two. // This means that if the map range is fully // contained the the placeholder we need to perform two split operations, // one at the start and at the end. const VAddr placeholder_start = it->lower(); const VAddr placeholder_end = it->upper(); const VAddr virtual_end = virtual_addr + aligned_size; // If the placeholder doesn't exactly start at virtual_addr, split it at the start. if (placeholder_start != virtual_addr) { VirtualFreeEx(process, reinterpret_cast<LPVOID>(placeholder_start), virtual_addr - placeholder_start, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER); } // If the placeholder doesn't exactly end at virtual_end, split it at the end. if (placeholder_end != virtual_end) { VirtualFreeEx(process, reinterpret_cast<LPVOID>(virtual_end), placeholder_end - virtual_end, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER); } // Remove the placeholder. placeholders.erase({virtual_addr, virtual_end}); // Perform the map. void* ptr = nullptr; if (phys_addr != -1) { HANDLE backing = fd ? reinterpret_cast<HANDLE>(fd) : backing_handle; if (fd && prot == PAGE_READONLY) { DWORD resultvar; ptr = VirtualAlloc2(process, reinterpret_cast<PVOID>(virtual_addr), aligned_size, MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0); bool ret = ReadFile(backing, ptr, size, &resultvar, NULL); ASSERT_MSG(ret, "ReadFile failed. {}", Common::GetLastErrorMsg()); ret = VirtualProtect(ptr, size, prot, &resultvar); ASSERT_MSG(ret, "VirtualProtect failed. {}", Common::GetLastErrorMsg()); } else { ptr = MapViewOfFile3(backing, process, reinterpret_cast<PVOID>(virtual_addr), phys_addr, aligned_size, MEM_REPLACE_PLACEHOLDER, prot, nullptr, 0); } } else { ptr = VirtualAlloc2(process, reinterpret_cast<PVOID>(virtual_addr), aligned_size, MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, prot, nullptr, 0); } ASSERT_MSG(ptr, "{}", Common::GetLastErrorMsg()); return ptr; } void Unmap(VAddr virtual_addr, size_t size, bool has_backing) { bool ret; if (has_backing) { ret = UnmapViewOfFile2(process, reinterpret_cast<PVOID>(virtual_addr), MEM_PRESERVE_PLACEHOLDER); } else { ret = VirtualFreeEx(process, reinterpret_cast<PVOID>(virtual_addr), size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER); } ASSERT_MSG(ret, "Unmap operation on virtual_addr={:#X} failed: {}", virtual_addr, Common::GetLastErrorMsg()); // The unmap call will create a new placeholder region. We need to see if we can coalesce it // with neighbors. VAddr placeholder_start = virtual_addr; VAddr placeholder_end = virtual_addr + size; // Check if a placeholder exists right before us. const auto left_it = placeholders.find(virtual_addr - 1); if (left_it != placeholders.end()) { ASSERT_MSG(left_it->upper() == virtual_addr, "Left placeholder does not end at virtual_addr!"); placeholder_start = left_it->lower(); VirtualFreeEx(process, reinterpret_cast<LPVOID>(placeholder_start), placeholder_end - placeholder_start, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS); } // Check if a placeholder exists right after us. const auto right_it = placeholders.find(placeholder_end + 1); if (right_it != placeholders.end()) { ASSERT_MSG(right_it->lower() == placeholder_end, "Right placeholder does not start at virtual_end!"); placeholder_end = right_it->upper(); VirtualFreeEx(process, reinterpret_cast<LPVOID>(placeholder_start), placeholder_end - placeholder_start, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS); } // Insert the new placeholder. placeholders.insert({placeholder_start, placeholder_end}); } void Protect(VAddr virtual_addr, size_t size, bool read, bool write, bool execute) { DWORD new_flags{}; if (read && write && execute) { new_flags = PAGE_EXECUTE_READWRITE; } else if (read && write) { new_flags = PAGE_READWRITE; } else if (read && !write) { new_flags = PAGE_READONLY; } else if (execute && !read && not write) { new_flags = PAGE_EXECUTE; } else if (!read && !write && !execute) { new_flags = PAGE_NOACCESS; } else { LOG_CRITICAL(Common_Memory, "Unsupported protection flag combination for address {:#x}, size {}", virtual_addr, size); return; } DWORD old_flags{}; bool success = VirtualProtect(reinterpret_cast<void*>(virtual_addr), size, new_flags, &old_flags); if (!success) { LOG_ERROR(Common_Memory, "Failed to change virtual memory protection for address {:#x}, size {}", virtual_addr, size); } // Use assert to ensure success in debug builds DEBUG_ASSERT(success && "Failed to change virtual memory protection"); } HANDLE process{}; HANDLE backing_handle{}; u8* backing_base{}; u8* virtual_base{}; u8* system_managed_base{}; size_t system_managed_size{}; u8* system_reserved_base{}; size_t system_reserved_size{}; u8* user_base{}; size_t user_size{}; boost::icl::separate_interval_set<uintptr_t> placeholders; }; #else enum PosixPageProtection { PAGE_NOACCESS = 0, PAGE_READONLY = PROT_READ, PAGE_READWRITE = PROT_READ | PROT_WRITE, PAGE_EXECUTE = PROT_EXEC, PAGE_EXECUTE_READ = PROT_EXEC | PROT_READ, PAGE_EXECUTE_READWRITE = PROT_EXEC | PROT_READ | PROT_WRITE }; [[nodiscard]] constexpr PosixPageProtection ToPosixProt(Core::MemoryProt prot) { if (True(prot & Core::MemoryProt::CpuReadWrite) || True(prot & Core::MemoryProt::GpuReadWrite)) { return PAGE_READWRITE; } else if (True(prot & Core::MemoryProt::CpuRead) || True(prot & Core::MemoryProt::GpuRead)) { return PAGE_READONLY; } else { return PAGE_NOACCESS; } } struct AddressSpace::Impl { Impl() { // Allocate virtual address placeholder for our address space. system_managed_size = SystemManagedSize; system_reserved_size = SystemReservedSize; user_size = UserSize; constexpr int protection_flags = PROT_READ | PROT_WRITE; constexpr int base_map_flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE; #if defined(__APPLE__) && defined(ARCH_X86_64) // On ARM64 Macs under Rosetta 2, we run into limitations due to the commpage from // 0xFC0000000 - 0xFFFFFFFFF and the GPU carveout region from 0x1000000000 - 0x6FFFFFFFFF. // We can allocate the system managed region, as well as system reserved if reduced in size // slightly, but we cannot map the user region where we want, so we must let the OS put it // wherever possible and hope the game won't rely on its location. system_managed_base = reinterpret_cast<u8*>( mmap(reinterpret_cast<void*>(SYSTEM_MANAGED_MIN), system_managed_size, protection_flags, base_map_flags | MAP_FIXED, -1, 0)); system_reserved_base = reinterpret_cast<u8*>( mmap(reinterpret_cast<void*>(SYSTEM_RESERVED_MIN), system_reserved_size, protection_flags, base_map_flags | MAP_FIXED, -1, 0)); // Cannot guarantee enough space for these areas at the desired addresses, so not MAP_FIXED. user_base = reinterpret_cast<u8*>(mmap(reinterpret_cast<void*>(USER_MIN), user_size, protection_flags, base_map_flags, -1, 0)); #else const auto virtual_size = system_managed_size + system_reserved_size + user_size; #if defined(ARCH_X86_64) const auto virtual_base = reinterpret_cast<u8*>(mmap(reinterpret_cast<void*>(SYSTEM_MANAGED_MIN), virtual_size, protection_flags, base_map_flags | MAP_FIXED, -1, 0)); system_managed_base = virtual_base; system_reserved_base = reinterpret_cast<u8*>(SYSTEM_RESERVED_MIN); user_base = reinterpret_cast<u8*>(USER_MIN); #else // Map memory wherever possible and instruction translation can handle offsetting to the // base. const auto virtual_base = reinterpret_cast<u8*>( mmap(nullptr, virtual_size, protection_flags, base_map_flags, -1, 0)); system_managed_base = virtual_base; system_reserved_base = virtual_base + SYSTEM_RESERVED_MIN - SYSTEM_MANAGED_MIN; user_base = virtual_base + USER_MIN - SYSTEM_MANAGED_MIN; #endif #endif if (system_managed_base == MAP_FAILED || system_reserved_base == MAP_FAILED || user_base == MAP_FAILED) { LOG_CRITICAL(Kernel_Vmm, "mmap failed: {}", strerror(errno)); throw std::bad_alloc{}; } LOG_INFO(Kernel_Vmm, "System managed virtual memory region: {} - {}", fmt::ptr(system_managed_base), fmt::ptr(system_managed_base + system_managed_size - 1)); LOG_INFO(Kernel_Vmm, "System reserved virtual memory region: {} - {}", fmt::ptr(system_reserved_base), fmt::ptr(system_reserved_base + system_reserved_size - 1)); LOG_INFO(Kernel_Vmm, "User virtual memory region: {} - {}", fmt::ptr(user_base), fmt::ptr(user_base + user_size - 1)); const VAddr system_managed_addr = reinterpret_cast<VAddr>(system_managed_base); const VAddr system_reserved_addr = reinterpret_cast<VAddr>(system_managed_base); const VAddr user_addr = reinterpret_cast<VAddr>(user_base); m_free_regions.insert({system_managed_addr, system_managed_addr + system_managed_size}); m_free_regions.insert({system_reserved_addr, system_reserved_addr + system_reserved_size}); m_free_regions.insert({user_addr, user_addr + user_size}); #ifdef __APPLE__ const auto shm_path = fmt::format("/BackingDmem{}", getpid()); backing_fd = shm_open(shm_path.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600); if (backing_fd < 0) { LOG_CRITICAL(Kernel_Vmm, "shm_open failed: {}", strerror(errno)); throw std::bad_alloc{}; } shm_unlink(shm_path.c_str()); #else madvise(virtual_base, virtual_size, MADV_HUGEPAGE); backing_fd = memfd_create("BackingDmem", 0); if (backing_fd < 0) { LOG_CRITICAL(Kernel_Vmm, "memfd_create failed: {}", strerror(errno)); throw std::bad_alloc{}; } #endif // Defined to extend the file with zeros int ret = ftruncate(backing_fd, BackingSize); if (ret != 0) { LOG_CRITICAL(Kernel_Vmm, "ftruncate failed with {}, are you out-of-memory?", strerror(errno)); throw std::bad_alloc{}; } // Map backing dmem handle. backing_base = static_cast<u8*>( mmap(nullptr, BackingSize, PROT_READ | PROT_WRITE, MAP_SHARED, backing_fd, 0)); if (backing_base == MAP_FAILED) { LOG_CRITICAL(Kernel_Vmm, "mmap failed: {}", strerror(errno)); throw std::bad_alloc{}; } } void* Map(VAddr virtual_addr, PAddr phys_addr, size_t size, PosixPageProtection prot, int fd = -1) { m_free_regions.subtract({virtual_addr, virtual_addr + size}); const int handle = phys_addr != -1 ? (fd == -1 ? backing_fd : fd) : -1; const off_t host_offset = phys_addr != -1 ? phys_addr : 0; const int flag = phys_addr != -1 ? MAP_SHARED : (MAP_ANONYMOUS | MAP_PRIVATE); void* ret = mmap(reinterpret_cast<void*>(virtual_addr), size, prot, MAP_FIXED | flag, handle, host_offset); ASSERT_MSG(ret != MAP_FAILED, "mmap failed: {}", strerror(errno)); return ret; } void Unmap(VAddr virtual_addr, size_t size, bool) { // Check to see if we are adjacent to any regions. auto start_address = virtual_addr; auto end_address = start_address + size; auto it = m_free_regions.find({start_address - 1, end_address + 1}); // If we are, join with them, ensuring we stay in bounds. if (it != m_free_regions.end()) { start_address = std::min(start_address, it->lower()); end_address = std::max(end_address, it->upper()); } // Free the relevant region. m_free_regions.insert({start_address, end_address}); // Return the adjusted pointers. void* ret = mmap(reinterpret_cast<void*>(start_address), end_address - start_address, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); ASSERT_MSG(ret != MAP_FAILED, "mmap failed: {}", strerror(errno)); } void Protect(VAddr virtual_addr, size_t size, bool read, bool write, bool execute) { int flags = PROT_NONE; if (read) { flags |= PROT_READ; } if (write) { flags |= PROT_WRITE; } #ifdef ARCH_X86_64 if (execute) { flags |= PROT_EXEC; } #endif int ret = mprotect(reinterpret_cast<void*>(virtual_addr), size, flags); ASSERT_MSG(ret == 0, "mprotect failed: {}", strerror(errno)); } int backing_fd; u8* backing_base{}; u8* system_managed_base{}; size_t system_managed_size{}; u8* system_reserved_base{}; size_t system_reserved_size{}; u8* user_base{}; size_t user_size{}; boost::icl::interval_set<VAddr> m_free_regions; }; #endif AddressSpace::AddressSpace() : impl{std::make_unique<Impl>()} { backing_base = impl->backing_base; system_managed_base = impl->system_managed_base; system_managed_size = impl->system_managed_size; system_reserved_base = impl->system_reserved_base; system_reserved_size = impl->system_reserved_size; user_base = impl->user_base; user_size = impl->user_size; } AddressSpace::~AddressSpace() = default; void* AddressSpace::Map(VAddr virtual_addr, size_t size, u64 alignment, PAddr phys_addr, bool is_exec) { #if ARCH_X86_64 const auto prot = is_exec ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE; #else // On non-native architectures, we can simplify things by ignoring the execute flag for the // canonical copy of the memory and rely on the JIT to map translated code as executable. constexpr auto prot = PAGE_READWRITE; #endif return impl->Map(virtual_addr, phys_addr, size, prot); } void* AddressSpace::MapFile(VAddr virtual_addr, size_t size, size_t offset, u32 prot, uintptr_t fd) { #ifdef _WIN32 return impl->Map(virtual_addr, offset, size, ToWindowsProt(std::bit_cast<Core::MemoryProt>(prot)), fd); #else return impl->Map(virtual_addr, offset, size, ToPosixProt(std::bit_cast<Core::MemoryProt>(prot)), fd); #endif } void AddressSpace::Unmap(VAddr virtual_addr, size_t size, VAddr start_in_vma, VAddr end_in_vma, PAddr phys_base, bool is_exec, bool has_backing, bool readonly_file) { #ifdef _WIN32 // There does not appear to be comparable support for partial unmapping on Windows. // Unfortunately, a least one title was found to require this. The workaround is to unmap // the entire allocation and remap the portions outside of the requested unmapping range. impl->Unmap(virtual_addr, size, has_backing && !readonly_file); // TODO: Determine if any titles require partial unmapping support for flexible allocations. ASSERT_MSG(has_backing || (start_in_vma == 0 && end_in_vma == size), "Partial unmapping of flexible allocations is not supported"); if (start_in_vma != 0) { Map(virtual_addr, start_in_vma, 0, phys_base, is_exec); } if (end_in_vma != size) { Map(virtual_addr + end_in_vma, size - end_in_vma, 0, phys_base + end_in_vma, is_exec); } #else impl->Unmap(virtual_addr + start_in_vma, end_in_vma - start_in_vma, has_backing); #endif } void AddressSpace::Protect(VAddr virtual_addr, size_t size, MemoryPermission perms) { const bool read = True(perms & MemoryPermission::Read); const bool write = True(perms & MemoryPermission::Write); const bool execute = True(perms & MemoryPermission::Execute); return impl->Protect(virtual_addr, size, read, write, execute); } } // namespace Core
23,953
C++
.cpp
471
40.785563
136
0.617214
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,546
module.cpp
shadps4-emu_shadPS4/src/core/module.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/alignment.h" #include "common/arch.h" #include "common/assert.h" #include "common/logging/log.h" #include "common/memory_patcher.h" #include "common/string_util.h" #include "core/aerolib/aerolib.h" #include "core/cpu_patches.h" #include "core/linker.h" #include "core/loader/dwarf.h" #include "core/memory.h" #include "core/module.h" namespace Core { using EntryFunc = PS4_SYSV_ABI int (*)(size_t args, const void* argp, void* param); static u64 LoadOffset = CODE_BASE_OFFSET; static constexpr u64 CODE_BASE_INCR = 0x010000000u; static u64 GetAlignedSize(const elf_program_header& phdr) { return (phdr.p_align != 0 ? (phdr.p_memsz + (phdr.p_align - 1)) & ~(phdr.p_align - 1) : phdr.p_memsz); } static u64 CalculateBaseSize(const elf_header& ehdr, std::span<const elf_program_header> phdr) { u64 base_size = 0; for (u16 i = 0; i < ehdr.e_phnum; i++) { if (phdr[i].p_memsz != 0 && (phdr[i].p_type == PT_LOAD || phdr[i].p_type == PT_SCE_RELRO)) { const u64 last_addr = phdr[i].p_vaddr + GetAlignedSize(phdr[i]); base_size = std::max(last_addr, base_size); } } return base_size; } static std::string EncodeId(u64 nVal) { std::string enc; static constexpr std::string_view codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-"; if (nVal < 0x40u) { enc += codes[nVal]; } else { if (nVal < 0x1000u) { enc += codes[static_cast<u16>(nVal >> 6u) & 0x3fu]; enc += codes[nVal & 0x3fu]; } else { enc += codes[static_cast<u16>(nVal >> 12u) & 0x3fu]; enc += codes[static_cast<u16>(nVal >> 6u) & 0x3fu]; enc += codes[nVal & 0x3fu]; } } return enc; } Module::Module(Core::MemoryManager* memory_, const std::filesystem::path& file_, u32& max_tls_index) : memory{memory_}, file{file_}, name{file.stem().string()} { elf.Open(file); if (elf.IsElfFile()) { LoadModuleToMemory(max_tls_index); LoadDynamicInfo(); LoadSymbols(); } } Module::~Module() = default; s32 Module::Start(size_t args, const void* argp, void* param) { LOG_INFO(Core_Linker, "Module started : {}", name); const auto* linker = Common::Singleton<Core::Linker>::Instance(); const VAddr addr = dynamic_info.init_virtual_addr + GetBaseAddress(); return linker->ExecuteGuest(reinterpret_cast<EntryFunc>(addr), args, argp, param); } void Module::LoadModuleToMemory(u32& max_tls_index) { static constexpr size_t BlockAlign = 0x1000; static constexpr u64 TrampolineSize = 8_MB; // Retrieve elf header and program header const auto elf_header = elf.GetElfHeader(); const auto elf_pheader = elf.GetProgramHeader(); const u64 base_size = CalculateBaseSize(elf_header, elf_pheader); aligned_base_size = Common::AlignUp(base_size, BlockAlign); // Map module segments (and possible TLS trampolines) void** out_addr = reinterpret_cast<void**>(&base_virtual_addr); memory->MapMemory(out_addr, memory->SystemReservedVirtualBase() + LoadOffset, aligned_base_size + TrampolineSize, MemoryProt::CpuReadWrite, MemoryMapFlags::Fixed, VMAType::Code, name, true); LoadOffset += CODE_BASE_INCR * (1 + aligned_base_size / CODE_BASE_INCR); LOG_INFO(Core_Linker, "Loading module {} to {}", name, fmt::ptr(*out_addr)); #ifdef ARCH_X86_64 // Initialize trampoline generator. void* trampoline_addr = std::bit_cast<void*>(base_virtual_addr + aligned_base_size); RegisterPatchModule(*out_addr, aligned_base_size, trampoline_addr, TrampolineSize); #endif LOG_INFO(Core_Linker, "======== Load Module to Memory ========"); LOG_INFO(Core_Linker, "base_virtual_addr ......: {:#018x}", base_virtual_addr); LOG_INFO(Core_Linker, "base_size ..............: {:#018x}", base_size); LOG_INFO(Core_Linker, "aligned_base_size ......: {:#018x}", aligned_base_size); const auto add_segment = [this](const elf_program_header& phdr, bool do_map = true) { const VAddr segment_addr = base_virtual_addr + phdr.p_vaddr; if (do_map) { elf.LoadSegment(segment_addr, phdr.p_offset, phdr.p_filesz); } auto& segment = info.segments[info.num_segments++]; segment.address = segment_addr; segment.prot = phdr.p_flags; segment.size = GetAlignedSize(phdr); }; for (u16 i = 0; i < elf_header.e_phnum; i++) { const auto header_type = elf.ElfPheaderTypeStr(elf_pheader[i].p_type); switch (elf_pheader[i].p_type) { case PT_LOAD: case PT_SCE_RELRO: { if (elf_pheader[i].p_memsz == 0) { LOG_ERROR(Core_Linker, "p_memsz==0 in type {}", header_type); continue; } const u64 segment_addr = elf_pheader[i].p_vaddr + base_virtual_addr; const u64 segment_file_size = elf_pheader[i].p_filesz; const u64 segment_memory_size = GetAlignedSize(elf_pheader[i]); const auto segment_mode = elf.ElfPheaderFlagsStr(elf_pheader[i].p_flags); LOG_INFO(Core_Linker, "program header = [{}] type = {}", i, header_type); LOG_INFO(Core_Linker, "segment_addr ..........: {:#018x}", segment_addr); LOG_INFO(Core_Linker, "segment_file_size .....: {}", segment_file_size); LOG_INFO(Core_Linker, "segment_memory_size ...: {}", segment_memory_size); LOG_INFO(Core_Linker, "segment_mode ..........: {}", segment_mode); add_segment(elf_pheader[i]); #ifdef ARCH_X86_64 if (elf_pheader[i].p_flags & PF_EXEC) { PrePatchInstructions(segment_addr, segment_file_size); } #endif break; } case PT_DYNAMIC: add_segment(elf_pheader[i], false); if (elf_pheader[i].p_filesz != 0) { m_dynamic.resize(elf_pheader[i].p_filesz); const VAddr segment_addr = std::bit_cast<VAddr>(m_dynamic.data()); elf.LoadSegment(segment_addr, elf_pheader[i].p_offset, elf_pheader[i].p_filesz); } else { LOG_ERROR(Core_Linker, "p_filesz==0 in type {}", header_type); } break; case PT_SCE_DYNLIBDATA: if (elf_pheader[i].p_filesz != 0) { m_dynamic_data.resize(elf_pheader[i].p_filesz); const VAddr segment_addr = std::bit_cast<VAddr>(m_dynamic_data.data()); elf.LoadSegment(segment_addr, elf_pheader[i].p_offset, elf_pheader[i].p_filesz); } else { LOG_ERROR(Core_Linker, "p_filesz==0 in type {}", header_type); } break; case PT_TLS: tls.init_image_size = elf_pheader[i].p_filesz; tls.align = elf_pheader[i].p_align; tls.image_virtual_addr = elf_pheader[i].p_vaddr + base_virtual_addr; tls.image_size = GetAlignedSize(elf_pheader[i]); if (tls.image_size != 0) { tls.modid = ++max_tls_index; } LOG_INFO(Core_Linker, "TLS virtual address = {:#x}", tls.image_virtual_addr); LOG_INFO(Core_Linker, "TLS image size = {}", tls.image_size); break; case PT_SCE_PROCPARAM: proc_param_virtual_addr = elf_pheader[i].p_vaddr + base_virtual_addr; break; case PT_GNU_EH_FRAME: { eh_frame_hdr_addr = elf_pheader[i].p_vaddr; eh_frame_hdr_size = elf_pheader[i].p_memsz; const VAddr eh_hdr_start = base_virtual_addr + eh_frame_hdr_addr; const VAddr eh_hdr_end = eh_hdr_start + eh_frame_hdr_size; Dwarf::EHHeaderInfo hdr_info; if (Dwarf::DecodeEHHdr(eh_hdr_start, eh_hdr_end, hdr_info)) { eh_frame_addr = hdr_info.eh_frame_ptr - base_virtual_addr; if (eh_frame_hdr_addr > eh_frame_addr) { eh_frame_size = (eh_frame_hdr_addr - eh_frame_addr); } else { eh_frame_size = (aligned_base_size - eh_frame_hdr_addr); } } break; } default: LOG_ERROR(Core_Linker, "Unimplemented type {}", header_type); } } const VAddr entry_addr = base_virtual_addr + elf.GetElfEntry(); LOG_INFO(Core_Linker, "program entry addr ..........: {:#018x}", entry_addr); if (MemoryPatcher::g_eboot_address == 0) { if (name == "eboot") { MemoryPatcher::g_eboot_address = base_virtual_addr; MemoryPatcher::g_eboot_image_size = base_size; MemoryPatcher::OnGameLoaded(); } } } void Module::LoadDynamicInfo() { for (const auto* dyn = reinterpret_cast<elf_dynamic*>(m_dynamic.data()); dyn->d_tag != DT_NULL; dyn++) { switch (dyn->d_tag) { case DT_SCE_HASH: // Offset of the hash table. dynamic_info.hash_table = reinterpret_cast<void*>(m_dynamic_data.data() + dyn->d_un.d_ptr); break; case DT_SCE_HASHSZ: // Size of the hash table dynamic_info.hash_table_size = dyn->d_un.d_val; break; case DT_SCE_STRTAB: // Offset of the string table. dynamic_info.str_table = reinterpret_cast<char*>(m_dynamic_data.data() + dyn->d_un.d_ptr); break; case DT_SCE_STRSZ: // Size of the string table. dynamic_info.str_table_size = dyn->d_un.d_val; break; case DT_SCE_SYMTAB: // Offset of the symbol table. dynamic_info.symbol_table = reinterpret_cast<elf_symbol*>(m_dynamic_data.data() + dyn->d_un.d_ptr); break; case DT_SCE_SYMTABSZ: // Size of the symbol table. dynamic_info.symbol_table_total_size = dyn->d_un.d_val; break; case DT_INIT: dynamic_info.init_virtual_addr = dyn->d_un.d_ptr; break; case DT_FINI: dynamic_info.fini_virtual_addr = dyn->d_un.d_ptr; break; case DT_SCE_PLTGOT: // Offset of the global offset table. dynamic_info.pltgot_virtual_addr = dyn->d_un.d_ptr; break; case DT_SCE_JMPREL: // Offset of the table containing jump slots. dynamic_info.jmp_relocation_table = reinterpret_cast<elf_relocation*>(m_dynamic_data.data() + dyn->d_un.d_ptr); break; case DT_SCE_PLTRELSZ: // Size of the global offset table. dynamic_info.jmp_relocation_table_size = dyn->d_un.d_val; break; case DT_SCE_PLTREL: // The type of relocations in the relocation table. Should be DT_RELA dynamic_info.jmp_relocation_type = dyn->d_un.d_val; if (dynamic_info.jmp_relocation_type != DT_RELA) { LOG_WARNING(Core_Linker, "DT_SCE_PLTREL is NOT DT_RELA should check!"); } break; case DT_SCE_RELA: // Offset of the relocation table. dynamic_info.relocation_table = reinterpret_cast<elf_relocation*>(m_dynamic_data.data() + dyn->d_un.d_ptr); break; case DT_SCE_RELASZ: // Size of the relocation table. dynamic_info.relocation_table_size = dyn->d_un.d_val; break; case DT_SCE_RELAENT: // The size of relocation table entries. dynamic_info.relocation_table_entries_size = dyn->d_un.d_val; if (dynamic_info.relocation_table_entries_size != 0x18) { LOG_WARNING(Core_Linker, "DT_SCE_RELAENT is NOT 0x18 should check!"); } break; case DT_INIT_ARRAY: // Address of the array of pointers to initialization functions dynamic_info.init_array_virtual_addr = dyn->d_un.d_ptr; break; case DT_FINI_ARRAY: // Address of the array of pointers to termination functions dynamic_info.fini_array_virtual_addr = dyn->d_un.d_ptr; break; case DT_INIT_ARRAYSZ: // Size in bytes of the array of initialization functions dynamic_info.init_array_size = dyn->d_un.d_val; break; case DT_FINI_ARRAYSZ: // Size in bytes of the array of terminationfunctions dynamic_info.fini_array_size = dyn->d_un.d_val; break; case DT_PREINIT_ARRAY: // Address of the array of pointers to pre - initialization functions dynamic_info.preinit_array_virtual_addr = dyn->d_un.d_ptr; break; case DT_PREINIT_ARRAYSZ: // Size in bytes of the array of pre - initialization functions dynamic_info.preinit_array_size = dyn->d_un.d_val; break; case DT_SCE_SYMENT: // The size of symbol table entries dynamic_info.symbol_table_entries_size = dyn->d_un.d_val; if (dynamic_info.symbol_table_entries_size != 0x18) { LOG_WARNING(Core_Linker, "DT_SCE_SYMENT is NOT 0x18 should check!"); } break; case DT_DEBUG: dynamic_info.debug = dyn->d_un.d_val; break; case DT_TEXTREL: dynamic_info.textrel = dyn->d_un.d_val; break; case DT_FLAGS: dynamic_info.flags = dyn->d_un.d_val; // This value should always be DF_TEXTREL (0x04) if (dynamic_info.flags != 0x04) { LOG_WARNING(Core_Linker, "DT_FLAGS is NOT 0x04 should check!"); } break; case DT_NEEDED: // Offset of the library string in the string table to be linked in. // In theory this should already be filled from about just make a test case if (dynamic_info.str_table) { dynamic_info.needed.push_back(dynamic_info.str_table + dyn->d_un.d_val); } else { LOG_ERROR(Core_Linker, "DT_NEEDED str table is not loaded should check!"); } break; case DT_SCE_NEEDED_MODULE: { ModuleInfo& info = dynamic_info.import_modules.emplace_back(); info.value = dyn->d_un.d_val; info.name = dynamic_info.str_table + info.name_offset; info.enc_id = EncodeId(info.id); break; } case DT_SCE_IMPORT_LIB: { LibraryInfo& info = dynamic_info.import_libs.emplace_back(); info.value = dyn->d_un.d_val; info.name = dynamic_info.str_table + info.name_offset; info.enc_id = EncodeId(info.id); break; } case DT_SCE_FINGERPRINT: // The fingerprint is a 24 byte (0x18) size buffer that contains a unique identifier for // the given app. How exactly this is generated isn't known, however it is not necessary // to have a valid fingerprint. While an invalid fingerprint will cause a warning to be // printed to the kernel log, the ELF will still load and run. LOG_INFO(Core_Linker, "DT_SCE_FINGERPRINT value = {:#018x}", dyn->d_un.d_val); std::memcpy(info.fingerprint.data(), &dyn->d_un.d_val, sizeof(SCE_DBG_NUM_FINGERPRINT)); break; case DT_SCE_IMPORT_LIB_ATTR: // The upper 32-bits should contain the module index multiplied by 0x10000. The lower // 32-bits should be a constant 0x9. LOG_INFO(Core_Linker, "unsupported DT_SCE_IMPORT_LIB_ATTR value = ......: {:#018x}", dyn->d_un.d_val); break; case DT_SCE_ORIGINAL_FILENAME: dynamic_info.filename = dynamic_info.str_table + dyn->d_un.d_val; break; case DT_SCE_MODULE_INFO: { ModuleInfo& info = dynamic_info.export_modules.emplace_back(); info.value = dyn->d_un.d_val; info.name = dynamic_info.str_table + info.name_offset; info.enc_id = EncodeId(info.id); const std::string full_name = info.name + ".sprx"; full_name.copy(this->info.name.data(), full_name.size()); break; }; case DT_SCE_MODULE_ATTR: LOG_INFO(Core_Linker, "unsupported DT_SCE_MODULE_ATTR value = ..........: {:#018x}", dyn->d_un.d_val); break; case DT_SCE_EXPORT_LIB: { LibraryInfo& info = dynamic_info.export_libs.emplace_back(); info.value = dyn->d_un.d_val; info.name = dynamic_info.str_table + info.name_offset; info.enc_id = EncodeId(info.id); break; } default: LOG_INFO(Core_Linker, "unsupported dynamic tag ..........: {:#018x}", dyn->d_tag); } } const u32 relabits_num = dynamic_info.relocation_table_size / sizeof(elf_relocation) + dynamic_info.jmp_relocation_table_size / sizeof(elf_relocation); rela_bits.resize((relabits_num + 7) / 8); } void Module::LoadSymbols() { const auto symbol_database = [this](Loader::SymbolsResolver& symbol, bool export_func) { if (!dynamic_info.symbol_table || !dynamic_info.str_table || dynamic_info.symbol_table_total_size == 0) { LOG_INFO(Core_Linker, "Symbol table not found!"); return; } for (auto* sym = dynamic_info.symbol_table; reinterpret_cast<u8*>(sym) < reinterpret_cast<u8*>(dynamic_info.symbol_table) + dynamic_info.symbol_table_total_size; sym++) { const u8 bind = sym->GetBind(); const u8 type = sym->GetType(); const u8 visibility = sym->GetVisibility(); const auto id = std::string(dynamic_info.str_table + sym->st_name); const auto ids = Common::SplitString(id, '#'); if (ids.size() != 3) { continue; } const auto* library = FindLibrary(ids[1]); const auto* module = FindModule(ids[2]); ASSERT_MSG(library && module, "Unable to find library and module"); if ((bind != STB_GLOBAL && bind != STB_WEAK) || (type != STT_FUN && type != STT_OBJECT) || export_func != (sym->st_value != 0)) { continue; } const auto aeronid = AeroLib::FindByNid(ids.at(0).c_str()); const auto nid_name = aeronid ? aeronid->name : "UNK"; Loader::SymbolResolver sym_r{}; sym_r.name = ids.at(0); sym_r.nidName = nid_name; sym_r.library = library->name; sym_r.library_version = library->version; sym_r.module = module->name; sym_r.module_version_major = module->version_major; sym_r.module_version_minor = module->version_minor; switch (type) { case STT_NOTYPE: sym_r.type = Loader::SymbolType::NoType; break; case STT_FUN: sym_r.type = Loader::SymbolType::Function; break; case STT_OBJECT: sym_r.type = Loader::SymbolType::Object; break; default: sym_r.type = Loader::SymbolType::Unknown; break; } const VAddr sym_addr = export_func ? sym->st_value + base_virtual_addr : 0; symbol.AddSymbol(sym_r, sym_addr); } }; symbol_database(export_sym, true); symbol_database(import_sym, false); } OrbisKernelModuleInfoEx Module::GetModuleInfoEx() const { return OrbisKernelModuleInfoEx{ .name = info.name, .tls_index = tls.modid, .tls_init_addr = tls.image_virtual_addr, .tls_init_size = tls.init_image_size, .tls_size = tls.image_size, .tls_offset = tls.offset, .tls_align = tls.align, .init_proc_addr = base_virtual_addr + dynamic_info.init_virtual_addr, .fini_proc_addr = base_virtual_addr + dynamic_info.fini_virtual_addr, .eh_frame_hdr_addr = eh_frame_hdr_addr, .eh_frame_addr = eh_frame_addr, .eh_frame_hdr_size = eh_frame_hdr_size, .eh_frame_size = eh_frame_size, .segments = info.segments, .segment_count = info.num_segments, }; } const ModuleInfo* Module::FindModule(std::string_view id) { const auto& import_modules = dynamic_info.import_modules; for (u32 i = 0; const auto& mod : import_modules) { if (mod.enc_id == id) { return &import_modules[i]; } i++; } const auto& export_modules = dynamic_info.export_modules; for (u32 i = 0; const auto& mod : export_modules) { if (mod.enc_id == id) { return &export_modules[i]; } i++; } return nullptr; } const LibraryInfo* Module::FindLibrary(std::string_view id) { const auto& import_libs = dynamic_info.import_libs; for (u32 i = 0; const auto& lib : import_libs) { if (lib.enc_id == id) { return &import_libs[i]; } i++; } const auto& export_libs = dynamic_info.export_libs; for (u32 i = 0; const auto& lib : export_libs) { if (lib.enc_id == id) { return &export_libs[i]; } i++; } return nullptr; } } // namespace Core
21,492
C++
.cpp
465
35.851613
100
0.579559
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,547
loader.cpp
shadps4-emu_shadPS4/src/core/loader.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/io_file.h" #include "common/types.h" #include "loader.h" namespace Loader { FileTypes DetectFileType(const std::filesystem::path& filepath) { // No file loaded if (filepath.empty()) { return FileTypes::Unknown; } Common::FS::IOFile file; file.Open(filepath, Common::FS::FileAccessMode::Read); file.Seek(0); u32 magic; file.Read(magic); file.Close(); switch (magic) { case PkgMagic: return FileTypes::Pkg; } return FileTypes::Unknown; } } // namespace Loader
659
C++
.cpp
24
23.458333
66
0.690967
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,548
libs.cpp
shadps4-emu_shadPS4/src/core/libraries/libs.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/config.h" #include "core/libraries/ajm/ajm.h" #include "core/libraries/app_content/app_content.h" #include "core/libraries/audio/audioin.h" #include "core/libraries/audio/audioout.h" #include "core/libraries/audio3d/audio3d.h" #include "core/libraries/avplayer/avplayer.h" #include "core/libraries/disc_map/disc_map.h" #include "core/libraries/game_live_streaming/gamelivestreaming.h" #include "core/libraries/gnmdriver/gnmdriver.h" #include "core/libraries/ime/error_dialog.h" #include "core/libraries/ime/ime.h" #include "core/libraries/ime/ime_dialog.h" #include "core/libraries/kernel/libkernel.h" #include "core/libraries/libc_internal/libc_internal.h" #include "core/libraries/libpng/pngdec.h" #include "core/libraries/libs.h" #include "core/libraries/network/http.h" #include "core/libraries/network/net.h" #include "core/libraries/network/netctl.h" #include "core/libraries/network/ssl.h" #include "core/libraries/np_manager/np_manager.h" #include "core/libraries/np_score/np_score.h" #include "core/libraries/np_trophy/np_trophy.h" #include "core/libraries/pad/pad.h" #include "core/libraries/playgo/playgo.h" #include "core/libraries/random/random.h" #include "core/libraries/remote_play/remoteplay.h" #include "core/libraries/rtc/rtc.h" #include "core/libraries/save_data/dialog/savedatadialog.h" #include "core/libraries/save_data/savedata.h" #include "core/libraries/screenshot/screenshot.h" #include "core/libraries/share_play/shareplay.h" #include "core/libraries/system/commondialog.h" #include "core/libraries/system/msgdialog.h" #include "core/libraries/system/posix.h" #include "core/libraries/system/sysmodule.h" #include "core/libraries/system/systemservice.h" #include "core/libraries/system/userservice.h" #include "core/libraries/usbd/usbd.h" #include "core/libraries/videodec/videodec.h" #include "core/libraries/videodec/videodec2.h" #include "core/libraries/videoout/video_out.h" namespace Libraries { void InitHLELibs(Core::Loader::SymbolsResolver* sym) { LOG_INFO(Lib_Kernel, "Initializing HLE libraries"); Libraries::Kernel::LibKernel_Register(sym); Libraries::GnmDriver::RegisterlibSceGnmDriver(sym); Libraries::VideoOut::RegisterLib(sym); // New libraries folder from autogen Libraries::UserService::RegisterlibSceUserService(sym); Libraries::SystemService::RegisterlibSceSystemService(sym); Libraries::CommonDialog::RegisterlibSceCommonDialog(sym); Libraries::MsgDialog::RegisterlibSceMsgDialog(sym); Libraries::AudioOut::RegisterlibSceAudioOut(sym); Libraries::Http::RegisterlibSceHttp(sym); Libraries::Net::RegisterlibSceNet(sym); Libraries::NetCtl::RegisterlibSceNetCtl(sym); Libraries::SaveData::RegisterlibSceSaveData(sym); Libraries::SaveData::Dialog::RegisterlibSceSaveDataDialog(sym); Libraries::Ssl::RegisterlibSceSsl(sym); Libraries::SysModule::RegisterlibSceSysmodule(sym); Libraries::Posix::Registerlibsceposix(sym); Libraries::AudioIn::RegisterlibSceAudioIn(sym); Libraries::NpManager::RegisterlibSceNpManager(sym); Libraries::NpScore::RegisterlibSceNpScore(sym); Libraries::NpTrophy::RegisterlibSceNpTrophy(sym); Libraries::ScreenShot::RegisterlibSceScreenShot(sym); Libraries::AppContent::RegisterlibSceAppContent(sym); Libraries::PngDec::RegisterlibScePngDec(sym); Libraries::PlayGo::RegisterlibScePlayGo(sym); Libraries::Random::RegisterlibSceRandom(sym); Libraries::Usbd::RegisterlibSceUsbd(sym); Libraries::Pad::RegisterlibScePad(sym); Libraries::Ajm::RegisterlibSceAjm(sym); Libraries::ErrorDialog::RegisterlibSceErrorDialog(sym); Libraries::ImeDialog::RegisterlibSceImeDialog(sym); Libraries::AvPlayer::RegisterlibSceAvPlayer(sym); Libraries::Vdec2::RegisterlibSceVdec2(sym); Libraries::Audio3d::RegisterlibSceAudio3d(sym); Libraries::Ime::RegisterlibSceIme(sym); Libraries::GameLiveStreaming::RegisterlibSceGameLiveStreaming(sym); Libraries::SharePlay::RegisterlibSceSharePlay(sym); Libraries::Remoteplay::RegisterlibSceRemoteplay(sym); Libraries::Videodec::RegisterlibSceVideodec(sym); } } // namespace Libraries
4,263
C++
.cpp
89
45.044944
71
0.795634
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,549
ime_dialog_ui.cpp
shadps4-emu_shadPS4/src/core/libraries/ime/ime_dialog_ui.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <cwchar> #include <string> #include <imgui.h> #include <magic_enum.hpp> #include "common/assert.h" #include "common/logging/log.h" #include "common/singleton.h" #include "core/libraries/ime/ime_dialog.h" #include "core/libraries/ime/ime_dialog_ui.h" #include "core/linker.h" #include "imgui/imgui_std.h" using namespace ImGui; static constexpr ImVec2 BUTTON_SIZE{100.0f, 30.0f}; namespace Libraries::ImeDialog { ImeDialogState::ImeDialogState(const OrbisImeDialogParam* param, const OrbisImeParamExtended* extended) { if (!param) { return; } userId = param->userId; is_multiLine = True(param->option & OrbisImeDialogOption::MULTILINE); is_numeric = param->type == OrbisImeType::NUMBER; type = param->type; enter_label = param->enterLabel; text_filter = param->filter; keyboard_filter = extended ? extended->extKeyboardFilter : nullptr; max_text_length = param->maxTextLength; text_buffer = param->inputTextBuffer; if (param->title) { std::size_t title_len = std::char_traits<char16_t>::length(param->title); title.resize(title_len * 4 + 1); title[title_len * 4] = '\0'; if (!ConvertOrbisToUTF8(param->title, title_len, &title[0], title_len * 4)) { LOG_ERROR(Lib_ImeDialog, "Failed to convert title to utf8 encoding"); } } if (param->placeholder) { std::size_t placeholder_len = std::char_traits<char16_t>::length(param->placeholder); placeholder.resize(placeholder_len * 4 + 1); placeholder[placeholder_len * 4] = '\0'; if (!ConvertOrbisToUTF8(param->placeholder, placeholder_len, &placeholder[0], placeholder_len * 4)) { LOG_ERROR(Lib_ImeDialog, "Failed to convert placeholder to utf8 encoding"); } } std::size_t text_len = std::char_traits<char16_t>::length(text_buffer); if (!ConvertOrbisToUTF8(text_buffer, text_len, current_text.begin(), ORBIS_IME_DIALOG_MAX_TEXT_LENGTH * 4)) { LOG_ERROR(Lib_ImeDialog, "Failed to convert text to utf8 encoding"); } } ImeDialogState::ImeDialogState(ImeDialogState&& other) noexcept : input_changed(other.input_changed), userId(other.userId), is_multiLine(other.is_multiLine), is_numeric(other.is_numeric), type(other.type), enter_label(other.enter_label), text_filter(other.text_filter), keyboard_filter(other.keyboard_filter), max_text_length(other.max_text_length), text_buffer(other.text_buffer), title(std::move(other.title)), placeholder(std::move(other.placeholder)), current_text(other.current_text) { other.text_buffer = nullptr; } ImeDialogState& ImeDialogState::operator=(ImeDialogState&& other) { if (this != &other) { input_changed = other.input_changed; userId = other.userId; is_multiLine = other.is_multiLine; is_numeric = other.is_numeric; type = other.type; enter_label = other.enter_label; text_filter = other.text_filter; keyboard_filter = other.keyboard_filter; max_text_length = other.max_text_length; text_buffer = other.text_buffer; title = std::move(other.title); placeholder = std::move(other.placeholder); current_text = other.current_text; other.text_buffer = nullptr; } return *this; } bool ImeDialogState::CopyTextToOrbisBuffer() { if (!text_buffer) { return false; } return ConvertUTF8ToOrbis(current_text.begin(), current_text.capacity(), text_buffer, max_text_length); } bool ImeDialogState::CallTextFilter() { if (!text_filter || !input_changed) { return true; } input_changed = false; char16_t src_text[ORBIS_IME_DIALOG_MAX_TEXT_LENGTH + 1] = {0}; u32 src_text_length = current_text.size(); char16_t out_text[ORBIS_IME_DIALOG_MAX_TEXT_LENGTH + 1] = {0}; u32 out_text_length = ORBIS_IME_DIALOG_MAX_TEXT_LENGTH; if (!ConvertUTF8ToOrbis(current_text.begin(), src_text_length, src_text, ORBIS_IME_DIALOG_MAX_TEXT_LENGTH)) { LOG_ERROR(Lib_ImeDialog, "Failed to convert text to orbis encoding"); return false; } auto* linker = Common::Singleton<Core::Linker>::Instance(); int ret = linker->ExecuteGuest(text_filter, out_text, &out_text_length, src_text, src_text_length); if (ret != 0) { return false; } if (!ConvertOrbisToUTF8(out_text, out_text_length, current_text.begin(), ORBIS_IME_DIALOG_MAX_TEXT_LENGTH * 4)) { LOG_ERROR(Lib_ImeDialog, "Failed to convert text to utf8 encoding"); return false; } return true; } bool ImeDialogState::CallKeyboardFilter(const OrbisImeKeycode* src_keycode, u16* out_keycode, u32* out_status) { if (!keyboard_filter) { return true; } auto* linker = Common::Singleton<Core::Linker>::Instance(); int ret = linker->ExecuteGuest(keyboard_filter, src_keycode, out_keycode, out_status, nullptr); return ret == 0; } bool ImeDialogState::ConvertOrbisToUTF8(const char16_t* orbis_text, std::size_t orbis_text_len, char* utf8_text, std::size_t utf8_text_len) { std::fill(utf8_text, utf8_text + utf8_text_len, '\0'); const ImWchar* orbis_text_ptr = reinterpret_cast<const ImWchar*>(orbis_text); ImTextStrToUtf8(utf8_text, utf8_text_len, orbis_text_ptr, orbis_text_ptr + orbis_text_len); return true; } bool ImeDialogState::ConvertUTF8ToOrbis(const char* utf8_text, std::size_t utf8_text_len, char16_t* orbis_text, std::size_t orbis_text_len) { std::fill(orbis_text, orbis_text + orbis_text_len, u'\0'); ImTextStrFromUtf8(reinterpret_cast<ImWchar*>(orbis_text), orbis_text_len, utf8_text, nullptr); return true; } ImeDialogUi::ImeDialogUi(ImeDialogState* state, OrbisImeDialogStatus* status, OrbisImeDialogResult* result) : state(state), status(status), result(result) { if (state && *status == OrbisImeDialogStatus::RUNNING) { AddLayer(this); } } ImeDialogUi::~ImeDialogUi() { std::scoped_lock lock(draw_mutex); Free(); } ImeDialogUi::ImeDialogUi(ImeDialogUi&& other) noexcept : state(other.state), status(other.status), result(other.result), first_render(other.first_render) { std::scoped_lock lock(draw_mutex, other.draw_mutex); other.state = nullptr; other.status = nullptr; other.result = nullptr; if (state && *status == OrbisImeDialogStatus::RUNNING) { AddLayer(this); } } ImeDialogUi& ImeDialogUi::operator=(ImeDialogUi&& other) { std::scoped_lock lock(draw_mutex, other.draw_mutex); Free(); state = other.state; status = other.status; result = other.result; first_render = other.first_render; other.state = nullptr; other.status = nullptr; other.result = nullptr; if (state && *status == OrbisImeDialogStatus::RUNNING) { AddLayer(this); } return *this; } void ImeDialogUi::Free() { RemoveLayer(this); } void ImeDialogUi::Draw() { std::unique_lock lock{draw_mutex}; if (!state) { return; } if (!status || *status != OrbisImeDialogStatus::RUNNING) { return; } const auto& ctx = *GetCurrentContext(); const auto& io = ctx.IO; ImVec2 window_size; if (state->is_multiLine) { window_size = {500.0f, 300.0f}; } else { window_size = {500.0f, 150.0f}; } CentralizeNextWindow(); SetNextWindowSize(window_size); SetNextWindowCollapsed(false); if (first_render || !io.NavActive) { SetNextWindowFocus(); } if (Begin("IME Dialog##ImeDialog", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoSavedSettings)) { DrawPrettyBackground(); if (!state->title.empty()) { SetWindowFontScale(1.7f); TextUnformatted(state->title.data()); SetWindowFontScale(1.0f); } if (state->is_multiLine) { DrawMultiLineInputText(); } else { DrawInputText(); } SetCursorPosY(GetCursorPosY() + 10.0f); const char* button_text; switch (state->enter_label) { case OrbisImeEnterLabel::GO: button_text = "Go##ImeDialogOK"; break; case OrbisImeEnterLabel::SEARCH: button_text = "Search##ImeDialogOK"; break; case OrbisImeEnterLabel::SEND: button_text = "Send##ImeDialogOK"; break; case OrbisImeEnterLabel::DEFAULT: default: button_text = "OK##ImeDialogOK"; break; } float button_spacing = 10.0f; float total_button_width = BUTTON_SIZE.x * 2 + button_spacing; float button_start_pos = (window_size.x - total_button_width) / 2.0f; SetCursorPosX(button_start_pos); if (Button(button_text, BUTTON_SIZE) || (!state->is_multiLine && IsKeyPressed(ImGuiKey_Enter))) { *status = OrbisImeDialogStatus::FINISHED; result->endstatus = OrbisImeDialogEndStatus::OK; } SameLine(0.0f, button_spacing); if (Button("Cancel##ImeDialogCancel", BUTTON_SIZE)) { *status = OrbisImeDialogStatus::FINISHED; result->endstatus = OrbisImeDialogEndStatus::USER_CANCELED; } } End(); first_render = false; } void ImeDialogUi::DrawInputText() { ImVec2 input_size = {GetWindowWidth() - 40.0f, 0.0f}; SetCursorPosX(20.0f); if (first_render) { SetKeyboardFocusHere(); } const char* placeholder = state->placeholder.empty() ? nullptr : state->placeholder.data(); if (InputTextEx("##ImeDialogInput", placeholder, state->current_text.begin(), state->max_text_length, input_size, ImGuiInputTextFlags_CallbackCharFilter, InputTextCallback, this)) { state->input_changed = true; } } void ImeDialogUi::DrawMultiLineInputText() { ImVec2 input_size = {GetWindowWidth() - 40.0f, 200.0f}; SetCursorPosX(20.0f); ImGuiInputTextFlags flags = ImGuiInputTextFlags_CallbackCharFilter | static_cast<ImGuiInputTextFlags>(ImGuiInputTextFlags_Multiline); if (first_render) { SetKeyboardFocusHere(); } const char* placeholder = state->placeholder.empty() ? nullptr : state->placeholder.data(); if (InputTextEx("##ImeDialogInput", placeholder, state->current_text.begin(), state->max_text_length, input_size, flags, InputTextCallback, this)) { state->input_changed = true; } } int ImeDialogUi::InputTextCallback(ImGuiInputTextCallbackData* data) { ImeDialogUi* ui = static_cast<ImeDialogUi*>(data->UserData); ASSERT(ui); // Should we filter punctuation? if (ui->state->is_numeric && (data->EventChar < '0' || data->EventChar > '9') && data->EventChar != '\b' && data->EventChar != ',' && data->EventChar != '.') { return 1; } if (!ui->state->keyboard_filter) { return 0; } // ImGui encodes ImWchar32 as multi-byte UTF-8 characters char* event_char = reinterpret_cast<char*>(&data->EventChar); // Call the keyboard filter OrbisImeKeycode src_keycode = { .keycode = 0, .character = 0, .status = 1, // ??? 1 = key pressed, 0 = key released .type = OrbisImeKeyboardType::ENGLISH_US, // TODO set this to the correct value (maybe use // the current language?) .userId = ui->state->userId, .resourceId = 0, .timestamp = 0}; if (!ui->state->ConvertUTF8ToOrbis(event_char, 4, &src_keycode.character, 1)) { LOG_ERROR(Lib_ImeDialog, "Failed to convert orbis char to utf8"); return 0; } src_keycode.keycode = src_keycode.character; // TODO set this to the correct value u16 out_keycode; u32 out_status; ui->state->CallKeyboardFilter(&src_keycode, &out_keycode, &out_status); // TODO. set the keycode return 0; } } // namespace Libraries::ImeDialog
12,522
C++
.cpp
309
32.954693
99
0.637023
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,550
error_dialog.cpp
shadps4-emu_shadPS4/src/core/libraries/ime/error_dialog.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <utility> #include <imgui.h> #include <magic_enum.hpp> #include "common/assert.h" #include "common/logging/log.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" #include "core/libraries/system/commondialog.h" #include "error_dialog.h" #include "imgui/imgui_layer.h" #include "imgui/imgui_std.h" static constexpr ImVec2 BUTTON_SIZE{100.0f, 30.0f}; namespace Libraries::ErrorDialog { using CommonDialog::Error; using CommonDialog::Result; using CommonDialog::Status; class ErrorDialogUi final : public ImGui::Layer { bool first_render{false}; Status* status{nullptr}; std::string err_message{}; public: explicit ErrorDialogUi(Status* status = nullptr, std::string err_message = "") : status(status), err_message(std::move(err_message)) { if (status && *status == Status::RUNNING) { first_render = true; AddLayer(this); } } ~ErrorDialogUi() override { Finish(); } ErrorDialogUi(const ErrorDialogUi& other) = delete; ErrorDialogUi(ErrorDialogUi&& other) noexcept : Layer(other), status(other.status), err_message(std::move(other.err_message)) { other.status = nullptr; } ErrorDialogUi& operator=(ErrorDialogUi other) { using std::swap; swap(status, other.status); swap(err_message, other.err_message); if (status && *status == Status::RUNNING) { first_render = true; AddLayer(this); } return *this; } void Finish() { if (status) { *status = Status::FINISHED; } status = nullptr; RemoveLayer(this); } void Draw() override { using namespace ImGui; if (status == nullptr || *status != Status::RUNNING) { return; } const auto& io = GetIO(); const ImVec2 window_size{ std::min(io.DisplaySize.x, 500.0f), std::min(io.DisplaySize.y, 300.0f), }; CentralizeNextWindow(); SetNextWindowSize(window_size); SetNextWindowCollapsed(false); if (first_render || !io.NavActive) { SetNextWindowFocus(); } KeepNavHighlight(); if (Begin("Error Dialog##ErrorDialog", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoSavedSettings)) { const auto ws = GetWindowSize(); DrawPrettyBackground(); const char* begin = &err_message.front(); const char* end = &err_message.back() + 1; SetWindowFontScale(1.3f); DrawCenteredText(begin, end, GetContentRegionAvail() - ImVec2{0.0f, 15.0f + BUTTON_SIZE.y}); SetWindowFontScale(1.0f); SetCursorPos({ ws.x / 2.0f - BUTTON_SIZE.x / 2.0f, ws.y - 10.0f - BUTTON_SIZE.y, }); if (Button("OK", BUTTON_SIZE)) { Finish(); } if (first_render) { SetItemCurrentNavFocus(); } } End(); first_render = false; } }; static auto g_status = Status::NONE; static ErrorDialogUi g_dialog_ui; struct Param { s32 size; s32 errorCode; OrbisUserServiceUserId userId; s32 _reserved; }; Error PS4_SYSV_ABI sceErrorDialogClose() { LOG_DEBUG(Lib_ErrorDialog, "called"); if (g_status != Status::RUNNING) { return Error::NOT_RUNNING; } g_dialog_ui.Finish(); return Error::OK; } Status PS4_SYSV_ABI sceErrorDialogGetStatus() { LOG_TRACE(Lib_ErrorDialog, "called status={}", magic_enum::enum_name(g_status)); return g_status; } Error PS4_SYSV_ABI sceErrorDialogInitialize() { LOG_DEBUG(Lib_ErrorDialog, "called"); if (g_status != Status::NONE) { return Error::ALREADY_INITIALIZED; } g_status = Status::INITIALIZED; return Error::OK; } Error PS4_SYSV_ABI sceErrorDialogOpen(const Param* param) { if (g_status != Status::INITIALIZED && g_status != Status::FINISHED) { LOG_INFO(Lib_ErrorDialog, "called without initialize"); return Error::INVALID_STATE; } if (param == nullptr) { LOG_DEBUG(Lib_ErrorDialog, "called param:(NULL)"); return Error::ARG_NULL; } const auto err = static_cast<u32>(param->errorCode); LOG_DEBUG(Lib_ErrorDialog, "called param->errorCode = {:#x}", err); ASSERT(param->size == sizeof(Param)); const std::string err_message = fmt::format("An error has occurred. \nCode: {:#X}", err); g_status = Status::RUNNING; g_dialog_ui = ErrorDialogUi{&g_status, err_message}; return Error::OK; } int PS4_SYSV_ABI sceErrorDialogOpenDetail() { LOG_ERROR(Lib_ErrorDialog, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceErrorDialogOpenWithReport() { LOG_ERROR(Lib_ErrorDialog, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceErrorDialogTerminate() { LOG_DEBUG(Lib_ErrorDialog, "called"); if (g_status == Status::RUNNING) { sceErrorDialogClose(); } if (g_status == Status::NONE) { return Error::NOT_INITIALIZED; } g_status = Status::NONE; return Error::OK; } Status PS4_SYSV_ABI sceErrorDialogUpdateStatus() { LOG_TRACE(Lib_ErrorDialog, "called status={}", magic_enum::enum_name(g_status)); return g_status; } void RegisterlibSceErrorDialog(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("ekXHb1kDBl0", "libSceErrorDialog", 1, "libSceErrorDialog", 1, 1, sceErrorDialogClose); LIB_FUNCTION("t2FvHRXzgqk", "libSceErrorDialog", 1, "libSceErrorDialog", 1, 1, sceErrorDialogGetStatus); LIB_FUNCTION("I88KChlynSs", "libSceErrorDialog", 1, "libSceErrorDialog", 1, 1, sceErrorDialogInitialize); LIB_FUNCTION("M2ZF-ClLhgY", "libSceErrorDialog", 1, "libSceErrorDialog", 1, 1, sceErrorDialogOpen); LIB_FUNCTION("jrpnVQfJYgQ", "libSceErrorDialog", 1, "libSceErrorDialog", 1, 1, sceErrorDialogOpenDetail); LIB_FUNCTION("wktCiyWoDTI", "libSceErrorDialog", 1, "libSceErrorDialog", 1, 1, sceErrorDialogOpenWithReport); LIB_FUNCTION("9XAxK2PMwk8", "libSceErrorDialog", 1, "libSceErrorDialog", 1, 1, sceErrorDialogTerminate); LIB_FUNCTION("WWiGuh9XfgQ", "libSceErrorDialog", 1, "libSceErrorDialog", 1, 1, sceErrorDialogUpdateStatus); }; } // namespace Libraries::ErrorDialog
6,639
C++
.cpp
184
29.027174
93
0.634412
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,551
ime_ui.cpp
shadps4-emu_shadPS4/src/core/libraries/ime/ime_ui.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "ime_ui.h" #include "imgui/imgui_std.h" namespace Libraries::Ime { using namespace ImGui; static constexpr ImVec2 BUTTON_SIZE{100.0f, 30.0f}; ImeState::ImeState(const OrbisImeParam* param) { if (!param) { return; } work_buffer = param->work; text_buffer = param->inputTextBuffer; std::size_t text_len = std::char_traits<char16_t>::length(text_buffer); if (!ConvertOrbisToUTF8(text_buffer, text_len, current_text.begin(), ORBIS_IME_MAX_TEXT_LENGTH * 4)) { LOG_ERROR(Lib_ImeDialog, "Failed to convert text to utf8 encoding"); } } ImeState::ImeState(ImeState&& other) noexcept : input_changed(other.input_changed), work_buffer(other.work_buffer), text_buffer(other.text_buffer), current_text(std::move(other.current_text)), event_queue(std::move(other.event_queue)) { other.text_buffer = nullptr; } ImeState& ImeState::operator=(ImeState&& other) noexcept { if (this != &other) { input_changed = other.input_changed; work_buffer = other.work_buffer; text_buffer = other.text_buffer; current_text = std::move(other.current_text); event_queue = std::move(other.event_queue); other.text_buffer = nullptr; } return *this; } void ImeState::SendEvent(OrbisImeEvent* event) { std::unique_lock lock{queue_mutex}; event_queue.push(*event); } void ImeState::SendEnterEvent() { OrbisImeEvent enterEvent{}; enterEvent.id = OrbisImeEventId::PRESS_ENTER; SendEvent(&enterEvent); } void ImeState::SendCloseEvent() { OrbisImeEvent closeEvent{}; closeEvent.id = OrbisImeEventId::PRESS_CLOSE; closeEvent.param.text.str = reinterpret_cast<char16_t*>(work_buffer); SendEvent(&closeEvent); } bool ImeState::ConvertOrbisToUTF8(const char16_t* orbis_text, std::size_t orbis_text_len, char* utf8_text, std::size_t utf8_text_len) { std::fill(utf8_text, utf8_text + utf8_text_len, '\0'); const ImWchar* orbis_text_ptr = reinterpret_cast<const ImWchar*>(orbis_text); ImTextStrToUtf8(utf8_text, utf8_text_len, orbis_text_ptr, orbis_text_ptr + orbis_text_len); return true; } bool ImeState::ConvertUTF8ToOrbis(const char* utf8_text, std::size_t utf8_text_len, char16_t* orbis_text, std::size_t orbis_text_len) { std::fill(orbis_text, orbis_text + orbis_text_len, u'\0'); ImTextStrFromUtf8(reinterpret_cast<ImWchar*>(orbis_text), orbis_text_len, utf8_text, nullptr); return true; } ImeUi::ImeUi(ImeState* state, const OrbisImeParam* param) : state(state), ime_param(param) { if (param) { AddLayer(this); } } ImeUi::~ImeUi() { std::scoped_lock lock(draw_mutex); Free(); } ImeUi& ImeUi::operator=(ImeUi&& other) { std::scoped_lock lock(draw_mutex, other.draw_mutex); Free(); state = other.state; ime_param = other.ime_param; first_render = other.first_render; other.state = nullptr; other.ime_param = nullptr; AddLayer(this); return *this; } void ImeUi::Draw() { std::unique_lock lock{draw_mutex}; if (!state) { return; } const auto& ctx = *GetCurrentContext(); const auto& io = ctx.IO; // TODO: Figure out how to properly translate the positions - // for example, if a game wants to center the IME panel, // we have to translate the panel position in a way that it // still becomes centered, as the game normally calculates // the position assuming a it's running on a 1920x1080 screen, // whereas we are running on a 1280x720 window size (by default). // // e.g. Panel position calculation from a game: // param.posx = (1920 / 2) - (panelWidth / 2); // param.posy = (1080 / 2) - (panelHeight / 2); const auto size = GetIO().DisplaySize; f32 pos_x = (ime_param->posx / 1920.0f * (float)size.x); f32 pos_y = (ime_param->posy / 1080.0f * (float)size.y); ImVec2 window_pos = {pos_x, pos_y}; ImVec2 window_size = {500.0f, 100.0f}; // SetNextWindowPos(window_pos); SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); SetNextWindowSize(window_size); SetNextWindowCollapsed(false); if (first_render || !io.NavActive) { SetNextWindowFocus(); } if (Begin("IME##Ime", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings)) { DrawPrettyBackground(); DrawInputText(); SetCursorPosY(GetCursorPosY() + 10.0f); const char* button_text; button_text = "Done##ImeDone"; float button_spacing = 10.0f; float total_button_width = BUTTON_SIZE.x * 2 + button_spacing; float button_start_pos = (window_size.x - total_button_width) / 2.0f; SetCursorPosX(button_start_pos); if (Button(button_text, BUTTON_SIZE) || (IsKeyPressed(ImGuiKey_Enter))) { state->SendEnterEvent(); } SameLine(0.0f, button_spacing); if (Button("Close##ImeClose", BUTTON_SIZE)) { state->SendCloseEvent(); } } End(); first_render = false; } void ImeUi::DrawInputText() { ImVec2 input_size = {GetWindowWidth() - 40.0f, 0.0f}; SetCursorPosX(20.0f); if (first_render) { SetKeyboardFocusHere(); } if (InputTextEx("##ImeInput", nullptr, state->current_text.begin(), ime_param->maxTextLength, input_size, ImGuiInputTextFlags_CallbackAlways, InputTextCallback, this)) { state->input_changed = true; } } int ImeUi::InputTextCallback(ImGuiInputTextCallbackData* data) { ImeUi* ui = static_cast<ImeUi*>(data->UserData); ASSERT(ui); static int lastCaretPos = -1; if (lastCaretPos == -1) { lastCaretPos = data->CursorPos; } else if (data->CursorPos != lastCaretPos) { OrbisImeCaretMovementDirection caretDirection = OrbisImeCaretMovementDirection::STILL; if (data->CursorPos < lastCaretPos) { caretDirection = OrbisImeCaretMovementDirection::LEFT; } else if (data->CursorPos > lastCaretPos) { caretDirection = OrbisImeCaretMovementDirection::RIGHT; } OrbisImeEvent event{}; event.id = OrbisImeEventId::UPDATE_CARET; event.param.caretMove = caretDirection; lastCaretPos = data->CursorPos; ui->state->SendEvent(&event); } static std::string lastText; std::string currentText(data->Buf, data->BufTextLen); if (currentText != lastText) { OrbisImeEditText eventParam{}; eventParam.str = reinterpret_cast<char16_t*>(ui->ime_param->work); eventParam.caretIndex = data->CursorPos; eventParam.areaNum = 1; eventParam.textArea[0].mode = 1; // Edit mode eventParam.textArea[0].index = data->CursorPos; eventParam.textArea[0].length = data->BufTextLen; if (!ui->state->ConvertUTF8ToOrbis(data->Buf, data->BufTextLen, eventParam.str, ui->ime_param->maxTextLength)) { LOG_ERROR(Lib_ImeDialog, "Failed to convert Orbis char to UTF-8"); return 0; } if (!ui->state->ConvertUTF8ToOrbis(data->Buf, data->BufTextLen, ui->ime_param->inputTextBuffer, ui->ime_param->maxTextLength)) { LOG_ERROR(Lib_ImeDialog, "Failed to convert Orbis char to UTF-8"); return 0; } OrbisImeEvent event{}; event.id = OrbisImeEventId::UPDATE_TEXT; event.param.text = eventParam; lastText = currentText; ui->state->SendEvent(&event); } return 0; } void ImeUi::Free() { RemoveLayer(this); } }; // namespace Libraries::Ime
8,350
C++
.cpp
200
33.31
99
0.624332
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,552
ime_dialog.cpp
shadps4-emu_shadPS4/src/core/libraries/ime/ime_dialog.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <array> #include <magic_enum.hpp> #include "common/logging/log.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" #include "ime_dialog.h" #include "ime_dialog_ui.h" static constexpr std::array<float, 2> MAX_X_POSITIONS = {3840.0f, 1920.0f}; static constexpr std::array<float, 2> MAX_Y_POSITIONS = {2160.0f, 1080.0f}; namespace Libraries::ImeDialog { static OrbisImeDialogStatus g_ime_dlg_status = OrbisImeDialogStatus::NONE; static OrbisImeDialogResult g_ime_dlg_result{}; static ImeDialogState g_ime_dlg_state{}; static ImeDialogUi g_ime_dlg_ui; static bool IsValidOption(OrbisImeDialogOption option, OrbisImeType type) { if (False(~option & (OrbisImeDialogOption::MULTILINE | OrbisImeDialogOption::NO_AUTO_COMPLETION))) { return false; } if (True(option & OrbisImeDialogOption::MULTILINE) && type != OrbisImeType::DEFAULT && type != OrbisImeType::BASIC_LATIN) { return false; } if (True(option & OrbisImeDialogOption::NO_AUTO_COMPLETION) && type != OrbisImeType::NUMBER && type != OrbisImeType::BASIC_LATIN) { return false; } return true; } Error PS4_SYSV_ABI sceImeDialogAbort() { if (g_ime_dlg_status == OrbisImeDialogStatus::NONE) { LOG_INFO(Lib_ImeDialog, "IME dialog not in use"); return Error::DIALOG_NOT_IN_USE; } if (g_ime_dlg_status != OrbisImeDialogStatus::RUNNING) { LOG_INFO(Lib_ImeDialog, "IME dialog not running"); return Error::DIALOG_NOT_RUNNING; } g_ime_dlg_status = OrbisImeDialogStatus::FINISHED; g_ime_dlg_result.endstatus = OrbisImeDialogEndStatus::ABORTED; return Error::OK; } Error PS4_SYSV_ABI sceImeDialogForceClose() { if (g_ime_dlg_status == OrbisImeDialogStatus::NONE) { LOG_INFO(Lib_ImeDialog, "IME dialog not in use"); return Error::DIALOG_NOT_IN_USE; } g_ime_dlg_status = OrbisImeDialogStatus::NONE; g_ime_dlg_ui = ImeDialogUi(); g_ime_dlg_state = ImeDialogState(); return Error::OK; } Error PS4_SYSV_ABI sceImeDialogForTestFunction() { return Error::INTERNAL; } int PS4_SYSV_ABI sceImeDialogGetCurrentStarState() { LOG_ERROR(Lib_ImeDialog, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDialogGetPanelPositionAndForm() { LOG_ERROR(Lib_ImeDialog, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDialogGetPanelSize() { LOG_ERROR(Lib_ImeDialog, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDialogGetPanelSizeExtended() { LOG_ERROR(Lib_ImeDialog, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceImeDialogGetResult(OrbisImeDialogResult* result) { if (g_ime_dlg_status == OrbisImeDialogStatus::NONE) { LOG_INFO(Lib_ImeDialog, "IME dialog is not running"); return Error::DIALOG_NOT_IN_USE; } if (result == nullptr) { LOG_INFO(Lib_ImeDialog, "called with result (NULL)"); return Error::INVALID_ADDRESS; } result->endstatus = g_ime_dlg_result.endstatus; if (g_ime_dlg_status == OrbisImeDialogStatus::RUNNING) { return Error::DIALOG_NOT_FINISHED; } g_ime_dlg_state.CopyTextToOrbisBuffer(); return Error::OK; } OrbisImeDialogStatus PS4_SYSV_ABI sceImeDialogGetStatus() { if (g_ime_dlg_status == OrbisImeDialogStatus::RUNNING) { g_ime_dlg_state.CallTextFilter(); } return g_ime_dlg_status; } Error PS4_SYSV_ABI sceImeDialogInit(OrbisImeDialogParam* param, OrbisImeParamExtended* extended) { if (g_ime_dlg_status != OrbisImeDialogStatus::NONE) { LOG_INFO(Lib_ImeDialog, "IME dialog is already running"); return Error::BUSY; } if (param == nullptr) { LOG_INFO(Lib_ImeDialog, "called with param (NULL)"); return Error::INVALID_ADDRESS; } if (!magic_enum::enum_contains(param->type)) { LOG_INFO(Lib_ImeDialog, "Invalid param->type"); return Error::INVALID_ADDRESS; } // TODO: do correct param->option validation // TODO: do correct param->supportedLanguages validation if (param->posx < 0.0f || param->posx >= MAX_X_POSITIONS[False(param->option & OrbisImeDialogOption::LARGE_RESOLUTION)]) { LOG_INFO(Lib_ImeDialog, "Invalid param->posx"); return Error::INVALID_POSX; } if (param->posy < 0.0f || param->posy >= MAX_Y_POSITIONS[False(param->option & OrbisImeDialogOption::LARGE_RESOLUTION)]) { LOG_INFO(Lib_ImeDialog, "Invalid param->posy"); return Error::INVALID_POSY; } if (!magic_enum::enum_contains(param->horizontalAlignment)) { LOG_INFO(Lib_ImeDialog, "Invalid param->horizontalAlignment"); return Error::INVALID_HORIZONTALIGNMENT; } if (!magic_enum::enum_contains(param->verticalAlignment)) { LOG_INFO(Lib_ImeDialog, "Invalid param->verticalAlignment"); return Error::INVALID_VERTICALALIGNMENT; } if (!IsValidOption(param->option, param->type)) { LOG_INFO(Lib_ImeDialog, "Invalid param->option"); return Error::INVALID_PARAM; } if (param->inputTextBuffer == nullptr) { LOG_INFO(Lib_ImeDialog, "Invalid param->inputTextBuffer"); return Error::INVALID_INPUT_TEXT_BUFFER; } if (extended) { if (!magic_enum::enum_contains(extended->priority)) { LOG_INFO(Lib_ImeDialog, "Invalid extended->priority"); return Error::INVALID_EXTENDED; } // TODO: do correct extended->option validation if ((extended->extKeyboardMode & 0xe3fffffc) != 0) { LOG_INFO(Lib_ImeDialog, "Invalid extended->extKeyboardMode"); return Error::INVALID_EXTENDED; } if (extended->disableDevice > 7) { LOG_INFO(Lib_ImeDialog, "Invalid extended->disableDevice"); return Error::INVALID_EXTENDED; } } if (param->maxTextLength > ORBIS_IME_DIALOG_MAX_TEXT_LENGTH) { LOG_INFO(Lib_ImeDialog, "Invalid param->maxTextLength"); return Error::INVALID_MAX_TEXT_LENGTH; } g_ime_dlg_result = {}; g_ime_dlg_state = ImeDialogState(param, extended); g_ime_dlg_status = OrbisImeDialogStatus::RUNNING; g_ime_dlg_ui = ImeDialogUi(&g_ime_dlg_state, &g_ime_dlg_status, &g_ime_dlg_result); return Error::OK; } int PS4_SYSV_ABI sceImeDialogInitInternal() { LOG_ERROR(Lib_ImeDialog, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDialogInitInternal2() { LOG_ERROR(Lib_ImeDialog, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDialogInitInternal3() { LOG_ERROR(Lib_ImeDialog, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDialogSetPanelPosition() { LOG_ERROR(Lib_ImeDialog, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceImeDialogTerm() { if (g_ime_dlg_status == OrbisImeDialogStatus::NONE) { LOG_INFO(Lib_ImeDialog, "IME dialog not in use"); return Error::DIALOG_NOT_IN_USE; } if (g_ime_dlg_status == OrbisImeDialogStatus::RUNNING) { LOG_INFO(Lib_ImeDialog, "IME dialog is still running"); return Error::DIALOG_NOT_FINISHED; } g_ime_dlg_status = OrbisImeDialogStatus::NONE; g_ime_dlg_ui = ImeDialogUi(); g_ime_dlg_state = ImeDialogState(); return Error::OK; } void RegisterlibSceImeDialog(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("oBmw4xrmfKs", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogAbort); LIB_FUNCTION("bX4H+sxPI-o", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogForceClose); LIB_FUNCTION("UFcyYDf+e88", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogForTestFunction); LIB_FUNCTION("fy6ntM25pEc", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogGetCurrentStarState); LIB_FUNCTION("8jqzzPioYl8", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogGetPanelPositionAndForm); LIB_FUNCTION("wqsJvRXwl58", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogGetPanelSize); LIB_FUNCTION("CRD+jSErEJQ", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogGetPanelSizeExtended); LIB_FUNCTION("x01jxu+vxlc", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogGetResult); LIB_FUNCTION("IADmD4tScBY", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogGetStatus); LIB_FUNCTION("NUeBrN7hzf0", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogInit); LIB_FUNCTION("KR6QDasuKco", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogInitInternal); LIB_FUNCTION("oe92cnJQ9HE", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogInitInternal2); LIB_FUNCTION("IoKIpNf9EK0", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogInitInternal3); LIB_FUNCTION("-2WqB87KKGg", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogSetPanelPosition); LIB_FUNCTION("gyTyVn+bXMw", "libSceImeDialog", 1, "libSceImeDialog", 1, 1, sceImeDialogTerm); }; } // namespace Libraries::ImeDialog
9,403
C++
.cpp
223
35.914798
98
0.679961
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,553
ime.cpp
shadps4-emu_shadPS4/src/core/libraries/ime/ime.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <queue> #include "ime.h" #include "ime_ui.h" #include "common/logging/log.h" #include "common/singleton.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" #include "core/linker.h" namespace Libraries::Ime { static std::queue<OrbisImeEvent> g_ime_events; static ImeState g_ime_state{}; static ImeUi g_ime_ui; class ImeHandler { public: ImeHandler(const OrbisImeKeyboardParam* param) { Init(param, false); } ImeHandler(const OrbisImeParam* param) { Init(param, true); } ~ImeHandler() = default; void Init(const void* param, bool ime_mode) { if (ime_mode) { m_param.ime = *(OrbisImeParam*)param; } else { m_param.key = *(OrbisImeKeyboardParam*)param; } m_ime_mode = ime_mode; // Open an event to let the game know the IME has started OrbisImeEvent openEvent{}; openEvent.id = (ime_mode ? OrbisImeEventId::OPEN : OrbisImeEventId::KEYBOARD_OPEN); if (ime_mode) { sceImeGetPanelSize(&m_param.ime, &openEvent.param.rect.width, &openEvent.param.rect.height); openEvent.param.rect.x = m_param.ime.posx; openEvent.param.rect.y = m_param.ime.posy; } else { openEvent.param.resourceIdArray.userId = 1; openEvent.param.resourceIdArray.resourceId[0] = 1; } Execute(nullptr, &openEvent, true); if (ime_mode) { g_ime_state = ImeState(&m_param.ime); g_ime_ui = ImeUi(&g_ime_state, &m_param.ime); } } s32 Update(OrbisImeEventHandler handler) { std::unique_lock lock{g_ime_state.queue_mutex}; while (!g_ime_state.event_queue.empty()) { OrbisImeEvent event = g_ime_state.event_queue.front(); g_ime_state.event_queue.pop(); Execute(handler, &event, false); } return ORBIS_OK; } void Execute(OrbisImeEventHandler handler, OrbisImeEvent* event, bool use_param_handler) { const auto* linker = Common::Singleton<Core::Linker>::Instance(); if (m_ime_mode) { OrbisImeParam param = m_param.ime; if (use_param_handler) { linker->ExecuteGuest(param.handler, param.arg, event); } else { linker->ExecuteGuest(handler, param.arg, event); } } else { OrbisImeKeyboardParam param = m_param.key; if (use_param_handler) { linker->ExecuteGuest(param.handler, param.arg, event); } else { linker->ExecuteGuest(handler, param.arg, event); } } } bool IsIme() { return m_ime_mode; } private: union ImeParam { OrbisImeKeyboardParam key; OrbisImeParam ime; } m_param{}; bool m_ime_mode = false; }; static std::unique_ptr<ImeHandler> g_ime_handler; int PS4_SYSV_ABI FinalizeImeModule() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI InitializeImeModule() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeCheckFilterText() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeCheckRemoteEventParam() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeCheckUpdateTextInfo() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } s32 PS4_SYSV_ABI sceImeClose() { LOG_INFO(Lib_Ime, "(STUBBED) called"); if (!g_ime_handler) { return ORBIS_IME_ERROR_NOT_OPENED; } if (!g_ime_handler->IsIme()) { return ORBIS_IME_ERROR_NOT_OPENED; } g_ime_handler.release(); g_ime_ui = ImeUi(); g_ime_state = ImeState(); return ORBIS_OK; } int PS4_SYSV_ABI sceImeConfigGet() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeConfigSet() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeConfirmCandidate() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDicAddWord() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDicDeleteLearnDics() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDicDeleteUserDics() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDicDeleteWord() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDicGetWords() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDicReplaceWord() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeDisableController() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeFilterText() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeForTestFunction() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeGetPanelPositionAndForm() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } s32 PS4_SYSV_ABI sceImeGetPanelSize(const OrbisImeParam* param, u32* width, u32* height) { LOG_INFO(Lib_Ime, "called"); if (!width || !height) { return ORBIS_IME_ERROR_INVALID_ADDRESS; } switch (param->type) { case OrbisImeType::DEFAULT: case OrbisImeType::BASIC_LATIN: case OrbisImeType::URL: case OrbisImeType::MAIL: // We set our custom sizes, commented sizes are the original ones *width = 500; // 793 *height = 100; // 408 break; case OrbisImeType::NUMBER: *width = 370; *height = 402; break; } return ORBIS_OK; } s32 PS4_SYSV_ABI sceImeKeyboardClose(s32 userId) { LOG_INFO(Lib_Ime, "(STUBBED) called"); if (!g_ime_handler) { return ORBIS_IME_ERROR_NOT_OPENED; } if (g_ime_handler->IsIme()) { return ORBIS_IME_ERROR_NOT_OPENED; } g_ime_handler.release(); return ORBIS_OK; } int PS4_SYSV_ABI sceImeKeyboardGetInfo() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeKeyboardGetResourceId() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } s32 PS4_SYSV_ABI sceImeKeyboardOpen(s32 userId, const OrbisImeKeyboardParam* param) { LOG_ERROR(Lib_Ime, "(STUBBED) called"); if (!param) { return ORBIS_IME_ERROR_INVALID_ADDRESS; } if (g_ime_handler) { return ORBIS_IME_ERROR_BUSY; } // g_ime_handler = std::make_unique<ImeHandler>(param); // return ORBIS_OK; return ORBIS_IME_ERROR_CONNECTION_FAILED; // Fixup } int PS4_SYSV_ABI sceImeKeyboardOpenInternal() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeKeyboardSetMode() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeKeyboardUpdate() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } s32 PS4_SYSV_ABI sceImeOpen(const OrbisImeParam* param, const void* extended) { LOG_INFO(Lib_Ime, "called"); if (!g_ime_handler) { g_ime_handler = std::make_unique<ImeHandler>(param); } else { if (g_ime_handler->IsIme()) { return ORBIS_IME_ERROR_BUSY; } g_ime_handler->Init((void*)param, true); } return ORBIS_OK; } int PS4_SYSV_ABI sceImeOpenInternal() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } void PS4_SYSV_ABI sceImeParamInit(OrbisImeParam* param) { LOG_INFO(Lib_Ime, "called"); if (!param) { return; } memset(param, 0, sizeof(OrbisImeParam)); param->userId = -1; } int PS4_SYSV_ABI sceImeSetCandidateIndex() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeSetCaret(const OrbisImeCaret* caret) { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeSetText() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeSetTextGeometry() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } s32 PS4_SYSV_ABI sceImeUpdate(OrbisImeEventHandler handler) { LOG_TRACE(Lib_Ime, "called"); if (!g_ime_handler) { return ORBIS_IME_ERROR_NOT_OPENED; } return g_ime_handler->Update(handler); } int PS4_SYSV_ABI sceImeVshClearPreedit() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshClose() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshConfirmPreedit() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshDisableController() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshGetPanelPositionAndForm() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshInformConfirmdString() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshInformConfirmdString2() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshOpen() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshSendTextInfo() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshSetCaretGeometry() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshSetCaretIndexInPreedit() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshSetPanelPosition() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshSetParam() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshSetPreeditGeometry() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshSetSelectGeometry() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshSetSelectionText() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshUpdate() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshUpdateContext() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceImeVshUpdateContext2() { LOG_ERROR(Lib_Ime, "(STUBBED) called"); return ORBIS_OK; } void RegisterlibSceIme(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("mN+ZoSN-8hQ", "libSceIme", 1, "libSceIme", 1, 1, FinalizeImeModule); LIB_FUNCTION("uTW+63goeJs", "libSceIme", 1, "libSceIme", 1, 1, InitializeImeModule); LIB_FUNCTION("Lf3DeGWC6xg", "libSceIme", 1, "libSceIme", 1, 1, sceImeCheckFilterText); LIB_FUNCTION("zHuMUGb-AQI", "libSceIme", 1, "libSceIme", 1, 1, sceImeCheckRemoteEventParam); LIB_FUNCTION("OTb0Mg+1i1k", "libSceIme", 1, "libSceIme", 1, 1, sceImeCheckUpdateTextInfo); LIB_FUNCTION("TmVP8LzcFcY", "libSceIme", 1, "libSceIme", 1, 1, sceImeClose); LIB_FUNCTION("Ho5NVQzpKHo", "libSceIme", 1, "libSceIme", 1, 1, sceImeConfigGet); LIB_FUNCTION("P5dPeiLwm-M", "libSceIme", 1, "libSceIme", 1, 1, sceImeConfigSet); LIB_FUNCTION("tKLmVIUkpyM", "libSceIme", 1, "libSceIme", 1, 1, sceImeConfirmCandidate); LIB_FUNCTION("NYDsL9a0oEo", "libSceIme", 1, "libSceIme", 1, 1, sceImeDicAddWord); LIB_FUNCTION("l01GKoyiQrY", "libSceIme", 1, "libSceIme", 1, 1, sceImeDicDeleteLearnDics); LIB_FUNCTION("E2OcGgi-FPY", "libSceIme", 1, "libSceIme", 1, 1, sceImeDicDeleteUserDics); LIB_FUNCTION("JAiMBkOTYKI", "libSceIme", 1, "libSceIme", 1, 1, sceImeDicDeleteWord); LIB_FUNCTION("JoPdCUXOzMU", "libSceIme", 1, "libSceIme", 1, 1, sceImeDicGetWords); LIB_FUNCTION("FuEl46uHDyo", "libSceIme", 1, "libSceIme", 1, 1, sceImeDicReplaceWord); LIB_FUNCTION("E+f1n8e8DAw", "libSceIme", 1, "libSceIme", 1, 1, sceImeDisableController); LIB_FUNCTION("evjOsE18yuI", "libSceIme", 1, "libSceIme", 1, 1, sceImeFilterText); LIB_FUNCTION("wVkehxutK-U", "libSceIme", 1, "libSceIme", 1, 1, sceImeForTestFunction); LIB_FUNCTION("T6FYjZXG93o", "libSceIme", 1, "libSceIme", 1, 1, sceImeGetPanelPositionAndForm); LIB_FUNCTION("ziPDcIjO0Vk", "libSceIme", 1, "libSceIme", 1, 1, sceImeGetPanelSize); LIB_FUNCTION("PMVehSlfZ94", "libSceIme", 1, "libSceIme", 1, 1, sceImeKeyboardClose); LIB_FUNCTION("VkqLPArfFdc", "libSceIme", 1, "libSceIme", 1, 1, sceImeKeyboardGetInfo); LIB_FUNCTION("dKadqZFgKKQ", "libSceIme", 1, "libSceIme", 1, 1, sceImeKeyboardGetResourceId); LIB_FUNCTION("eaFXjfJv3xs", "libSceIme", 1, "libSceIme", 1, 1, sceImeKeyboardOpen); LIB_FUNCTION("oYkJlMK51SA", "libSceIme", 1, "libSceIme", 1, 1, sceImeKeyboardOpenInternal); LIB_FUNCTION("ua+13Hk9kKs", "libSceIme", 1, "libSceIme", 1, 1, sceImeKeyboardSetMode); LIB_FUNCTION("3Hx2Uw9xnv8", "libSceIme", 1, "libSceIme", 1, 1, sceImeKeyboardUpdate); LIB_FUNCTION("RPydv-Jr1bc", "libSceIme", 1, "libSceIme", 1, 1, sceImeOpen); LIB_FUNCTION("16UI54cWRQk", "libSceIme", 1, "libSceIme", 1, 1, sceImeOpenInternal); LIB_FUNCTION("WmYDzdC4EHI", "libSceIme", 1, "libSceIme", 1, 1, sceImeParamInit); LIB_FUNCTION("TQaogSaqkEk", "libSceIme", 1, "libSceIme", 1, 1, sceImeSetCandidateIndex); LIB_FUNCTION("WLxUN2WMim8", "libSceIme", 1, "libSceIme", 1, 1, sceImeSetCaret); LIB_FUNCTION("ieCNrVrzKd4", "libSceIme", 1, "libSceIme", 1, 1, sceImeSetText); LIB_FUNCTION("TXYHFRuL8UY", "libSceIme", 1, "libSceIme", 1, 1, sceImeSetTextGeometry); LIB_FUNCTION("-4GCfYdNF1s", "libSceIme", 1, "libSceIme", 1, 1, sceImeUpdate); LIB_FUNCTION("oOwl47ouxoM", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshClearPreedit); LIB_FUNCTION("gtoTsGM9vEY", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshClose); LIB_FUNCTION("wTKF4mUlSew", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshConfirmPreedit); LIB_FUNCTION("rM-1hkuOhh0", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshDisableController); LIB_FUNCTION("42xMaQ+GLeQ", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshGetPanelPositionAndForm); LIB_FUNCTION("ZmmV6iukhyo", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshInformConfirmdString); LIB_FUNCTION("EQBusz6Uhp8", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshInformConfirmdString2); LIB_FUNCTION("LBicRa-hj3A", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshOpen); LIB_FUNCTION("-IAOwd2nO7g", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshSendTextInfo); LIB_FUNCTION("qDagOjvJdNk", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshSetCaretGeometry); LIB_FUNCTION("tNOlmxee-Nk", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshSetCaretIndexInPreedit); LIB_FUNCTION("rASXozKkQ9g", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshSetPanelPosition); LIB_FUNCTION("idvMaIu5H+k", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshSetParam); LIB_FUNCTION("ga5GOgThbjo", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshSetPreeditGeometry); LIB_FUNCTION("RuSca8rS6yA", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshSetSelectGeometry); LIB_FUNCTION("J7COZrgSFRA", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshSetSelectionText); LIB_FUNCTION("WqAayyok5p0", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshUpdate); LIB_FUNCTION("O7Fdd+Oc-qQ", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshUpdateContext); LIB_FUNCTION("fwcPR7+7Rks", "libSceIme", 1, "libSceIme", 1, 1, sceImeVshUpdateContext2); }; } // namespace Libraries::Ime
15,865
C++
.cpp
416
33.115385
100
0.672852
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,554
libc_internal.cpp
shadps4-emu_shadPS4/src/core/libraries/libc_internal/libc_internal.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <cmath> #include "common/logging/log.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" #include "libc_internal.h" namespace Libraries::LibcInternal { void* PS4_SYSV_ABI internal_memset(void* s, int c, size_t n) { return std::memset(s, c, n); } void* PS4_SYSV_ABI internal_memcpy(void* dest, const void* src, size_t n) { return std::memcpy(dest, src, n); } int PS4_SYSV_ABI internal_memcpy_s(void* dest, size_t destsz, const void* src, size_t count) { #ifdef _WIN64 return memcpy_s(dest, destsz, src, count); #else std::memcpy(dest, src, count); return 0; // ALL OK #endif } int PS4_SYSV_ABI internal_strcpy_s(char* dest, size_t dest_size, const char* src) { #ifdef _WIN64 return strcpy_s(dest, dest_size, src); #else std::strcpy(dest, src); return 0; // ALL OK #endif } int PS4_SYSV_ABI internal_memcmp(const void* s1, const void* s2, size_t n) { return std::memcmp(s1, s2, n); } int PS4_SYSV_ABI internal_strncmp(const char* str1, const char* str2, size_t num) { return std::strncmp(str1, str2, num); } int PS4_SYSV_ABI internal_strlen(const char* str) { return std::strlen(str); } float PS4_SYSV_ABI internal_expf(float x) { return expf(x); } void* PS4_SYSV_ABI internal_malloc(size_t size) { return std::malloc(size); } char* PS4_SYSV_ABI internal_strncpy(char* dest, const char* src, std::size_t count) { return std::strncpy(dest, src, count); } void RegisterlibSceLibcInternal(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("NFLs+dRJGNg", "libSceLibcInternal", 1, "libSceLibcInternal", 1, 1, internal_memcpy_s); LIB_FUNCTION("Q3VBxCXhUHs", "libSceLibcInternal", 1, "libSceLibcInternal", 1, 1, internal_memcpy); LIB_FUNCTION("8zTFvBIAIN8", "libSceLibcInternal", 1, "libSceLibcInternal", 1, 1, internal_memset); LIB_FUNCTION("5Xa2ACNECdo", "libSceLibcInternal", 1, "libSceLibcInternal", 1, 1, internal_strcpy_s); LIB_FUNCTION("DfivPArhucg", "libSceLibcInternal", 1, "libSceLibcInternal", 1, 1, internal_memcmp); LIB_FUNCTION("8zsu04XNsZ4", "libSceLibcInternal", 1, "libSceLibcInternal", 1, 1, internal_expf); LIB_FUNCTION("aesyjrHVWy4", "libSceLibcInternal", 1, "libSceLibcInternal", 1, 1, internal_strncmp); LIB_FUNCTION("j4ViWNHEgww", "libSceLibcInternal", 1, "libSceLibcInternal", 1, 1, internal_strlen); LIB_FUNCTION("6sJWiWSRuqk", "libSceLibcInternal", 1, "libSceLibcInternal", 1, 1, internal_strncpy); LIB_FUNCTION("gQX+4GDQjpM", "libSceLibcInternal", 1, "libSceLibcInternal", 1, 1, internal_malloc); }; } // namespace Libraries::LibcInternal
2,867
C++
.cpp
70
36.185714
100
0.685119
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,555
disc_map.cpp
shadps4-emu_shadPS4/src/core/libraries/disc_map/disc_map.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/logging/log.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" #include "disc_map.h" #include "disc_map_codes.h" namespace Libraries::DiscMap { int PS4_SYSV_ABI sceDiscMapGetPackageSize() { LOG_WARNING(Lib_DiscMap, "(DUMMY) called"); return ORBIS_DISC_MAP_ERROR_NO_BITMAP_INFO; } int PS4_SYSV_ABI sceDiscMapIsRequestOnHDD() { LOG_WARNING(Lib_DiscMap, "(DUMMY) called"); return ORBIS_DISC_MAP_ERROR_NO_BITMAP_INFO; } int PS4_SYSV_ABI Func_7C980FFB0AA27E7A() { LOG_ERROR(Lib_DiscMap, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_8A828CAEE7EDD5E9() { LOG_ERROR(Lib_DiscMap, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_E7EBCE96E92F91F8() { LOG_ERROR(Lib_DiscMap, "(STUBBED) called"); return ORBIS_OK; } void RegisterlibSceDiscMap(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("fl1eoDnwQ4s", "libSceDiscMap", 1, "libSceDiscMap", 1, 1, sceDiscMapGetPackageSize); LIB_FUNCTION("lbQKqsERhtE", "libSceDiscMap", 1, "libSceDiscMap", 1, 1, sceDiscMapIsRequestOnHDD); LIB_FUNCTION("fJgP+wqifno", "libSceDiscMap", 1, "libSceDiscMap", 1, 1, Func_7C980FFB0AA27E7A); LIB_FUNCTION("ioKMruft1ek", "libSceDiscMap", 1, "libSceDiscMap", 1, 1, Func_8A828CAEE7EDD5E9); LIB_FUNCTION("5+vOlukvkfg", "libSceDiscMap", 1, "libSceDiscMap", 1, 1, Func_E7EBCE96E92F91F8); }; } // namespace Libraries::DiscMap
1,574
C++
.cpp
38
37.710526
98
0.723641
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,556
app_content.cpp
shadps4-emu_shadPS4/src/core/libraries/app_content/app_content.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <cmath> #include "app_content.h" #include "common/assert.h" #include "common/config.h" #include "common/io_file.h" #include "common/logging/log.h" #include "common/path_util.h" #include "common/singleton.h" #include "common/string_util.h" #include "core/file_format/psf.h" #include "core/file_sys/fs.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" namespace Libraries::AppContent { int32_t addcont_count = 0; struct AddContInfo { char entitlementLabel[ORBIS_NP_UNIFIED_ENTITLEMENT_LABEL_SIZE]; OrbisAppContentAddcontDownloadStatus status; OrbisAppContentGetEntitlementKey key; }; std::array<AddContInfo, ORBIS_APP_CONTENT_INFO_LIST_MAX_SIZE> addcont_info = {{ {"0000000000000000", ORBIS_APP_CONTENT_ADDCONT_DOWNLOAD_STATUS_INSTALLED, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, }}; std::string title_id; int PS4_SYSV_ABI _Z5dummyv() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentAddcontDelete() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentAddcontEnqueueDownload() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentAddcontEnqueueDownloadSp() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentAddcontMount(u32 service_label, const OrbisNpUnifiedEntitlementLabel* entitlement_label, OrbisAppContentMountPoint* mount_point) { LOG_INFO(Lib_AppContent, "called"); const auto& mount_dir = Config::getAddonInstallDir() / title_id / entitlement_label->data; auto* mnt = Common::Singleton<Core::FileSys::MntPoints>::Instance(); for (int i = 0; i < addcont_count; i++) { if (strncmp(entitlement_label->data, addcont_info[i].entitlementLabel, ORBIS_NP_UNIFIED_ENTITLEMENT_LABEL_SIZE - 1) != 0) { continue; } if (addcont_info[i].status != ORBIS_APP_CONTENT_ADDCONT_DOWNLOAD_STATUS_INSTALLED) { return ORBIS_APP_CONTENT_ERROR_NOT_FOUND; } snprintf(mount_point->data, ORBIS_APP_CONTENT_MOUNTPOINT_DATA_MAXSIZE, "/addcont%d", i); mnt->Mount(mount_dir, mount_point->data); return ORBIS_OK; } return ORBIS_APP_CONTENT_ERROR_NOT_FOUND; } int PS4_SYSV_ABI sceAppContentAddcontShrink() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentAddcontUnmount() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentAppParamGetInt(OrbisAppContentAppParamId paramId, s32* out_value) { if (out_value == nullptr) return ORBIS_APP_CONTENT_ERROR_PARAMETER; auto* param_sfo = Common::Singleton<PSF>::Instance(); std::optional<s32> value; switch (paramId) { case ORBIS_APP_CONTENT_APPPARAM_ID_SKU_FLAG: value = ORBIS_APP_CONTENT_APPPARAM_SKU_FLAG_FULL; break; case ORBIS_APP_CONTENT_APPPARAM_ID_USER_DEFINED_PARAM_1: value = param_sfo->GetInteger("USER_DEFINED_PARAM_1"); break; case ORBIS_APP_CONTENT_APPPARAM_ID_USER_DEFINED_PARAM_2: value = param_sfo->GetInteger("USER_DEFINED_PARAM_2"); break; case ORBIS_APP_CONTENT_APPPARAM_ID_USER_DEFINED_PARAM_3: value = param_sfo->GetInteger("USER_DEFINED_PARAM_3"); break; case ORBIS_APP_CONTENT_APPPARAM_ID_USER_DEFINED_PARAM_4: value = param_sfo->GetInteger("USER_DEFINED_PARAM_4"); break; default: LOG_ERROR(Lib_AppContent, " paramId = {} paramId is not valid", paramId); return ORBIS_APP_CONTENT_ERROR_PARAMETER; } *out_value = value.value_or(0); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentAppParamGetString() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentDownload0Expand() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentDownload0Shrink() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentDownload1Expand() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentDownload1Shrink() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentDownloadDataFormat() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentDownloadDataGetAvailableSpaceKb() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentGetAddcontDownloadProgress() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentGetAddcontInfo(u32 service_label, const OrbisNpUnifiedEntitlementLabel* entitlementLabel, OrbisAppContentAddcontInfo* info) { LOG_INFO(Lib_AppContent, "called"); if (entitlementLabel == nullptr || info == nullptr) { return ORBIS_APP_CONTENT_ERROR_PARAMETER; } for (auto i = 0; i < addcont_count; i++) { if (strncmp(entitlementLabel->data, addcont_info[i].entitlementLabel, ORBIS_NP_UNIFIED_ENTITLEMENT_LABEL_SIZE - 1) != 0) { continue; } LOG_INFO(Lib_AppContent, "found DLC {}", entitlementLabel->data); strncpy(info->entitlement_label.data, addcont_info[i].entitlementLabel, ORBIS_NP_UNIFIED_ENTITLEMENT_LABEL_SIZE); info->status = addcont_info[i].status; return ORBIS_OK; } return ORBIS_APP_CONTENT_ERROR_DRM_NO_ENTITLEMENT; } int PS4_SYSV_ABI sceAppContentGetAddcontInfoList(u32 service_label, OrbisAppContentAddcontInfo* list, u32 list_num, u32* hit_num) { LOG_INFO(Lib_AppContent, "called"); if (list_num == 0 || list == nullptr) { if (hit_num == nullptr) { return ORBIS_APP_CONTENT_ERROR_PARAMETER; } *hit_num = addcont_count; return ORBIS_OK; } int dlcs_to_list = addcont_count < list_num ? addcont_count : list_num; for (int i = 0; i < dlcs_to_list; i++) { strncpy(list[i].entitlement_label.data, addcont_info[i].entitlementLabel, ORBIS_NP_UNIFIED_ENTITLEMENT_LABEL_SIZE); list[i].status = addcont_info[i].status; } if (hit_num != nullptr) { *hit_num = dlcs_to_list; } return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentGetEntitlementKey( u32 service_label, const OrbisNpUnifiedEntitlementLabel* entitlement_label, OrbisAppContentGetEntitlementKey* key) { LOG_ERROR(Lib_AppContent, "called"); if (entitlement_label == nullptr || key == nullptr) { return ORBIS_APP_CONTENT_ERROR_PARAMETER; } for (int i = 0; i < addcont_count; i++) { if (strncmp(entitlement_label->data, addcont_info[i].entitlementLabel, ORBIS_NP_UNIFIED_ENTITLEMENT_LABEL_SIZE - 1) != 0) { continue; } memcpy(key->data, addcont_info[i].key.data, ORBIS_APP_CONTENT_ENTITLEMENT_KEY_SIZE); return ORBIS_OK; } return ORBIS_APP_CONTENT_ERROR_DRM_NO_ENTITLEMENT; } int PS4_SYSV_ABI sceAppContentGetRegion() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentInitialize(const OrbisAppContentInitParam* initParam, OrbisAppContentBootParam* bootParam) { LOG_ERROR(Lib_AppContent, "(DUMMY) called"); auto* param_sfo = Common::Singleton<PSF>::Instance(); const auto addons_dir = Config::getAddonInstallDir(); if (const auto value = param_sfo->GetString("TITLE_ID"); value.has_value()) { title_id = *value; } else { UNREACHABLE_MSG("Failed to get TITLE_ID"); } auto addon_path = addons_dir / title_id; if (std::filesystem::exists(addon_path)) { for (const auto& entry : std::filesystem::directory_iterator(addon_path)) { if (entry.is_directory()) { auto entitlement_label = entry.path().filename().string(); AddContInfo info{}; info.status = ORBIS_APP_CONTENT_ADDCONT_DOWNLOAD_STATUS_INSTALLED; strcpy(info.entitlementLabel, entitlement_label.c_str()); addcont_info[addcont_count++] = info; } } } return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentRequestPatchInstall() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentSmallSharedDataFormat() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentSmallSharedDataGetAvailableSpaceKb() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentSmallSharedDataMount() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentSmallSharedDataUnmount() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentTemporaryDataFormat() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentTemporaryDataGetAvailableSpaceKb( const OrbisAppContentMountPoint* mountPoint, size_t* availableSpaceKb) { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); *availableSpaceKb = 1073741824; return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentTemporaryDataMount() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentTemporaryDataMount2(OrbisAppContentTemporaryDataOption option, OrbisAppContentMountPoint* mountPoint) { if (mountPoint == nullptr) return ORBIS_APP_CONTENT_ERROR_PARAMETER; strncpy(mountPoint->data, "/temp0", 16); LOG_INFO(Lib_AppContent, "sceAppContentTemporaryDataMount2: option = {}, mountPoint = {}", option, mountPoint->data); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentTemporaryDataUnmount() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentGetPftFlag() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_C59A36FF8D7C59DA() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentAddcontEnqueueDownloadByEntitlementId() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentAddcontMountByEntitlementId() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentGetAddcontInfoByEntitlementId() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentGetAddcontInfoListByIroTag() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceAppContentGetDownloadedStoreCountry() { LOG_ERROR(Lib_AppContent, "(STUBBED) called"); return ORBIS_OK; } void RegisterlibSceAppContent(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("AS45QoYHjc4", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, _Z5dummyv); LIB_FUNCTION("ZiATpP9gEkA", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentAddcontDelete); LIB_FUNCTION("7gxh+5QubhY", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentAddcontEnqueueDownload); LIB_FUNCTION("TVM-aYIsG9k", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentAddcontEnqueueDownloadSp); LIB_FUNCTION("VANhIWcqYak", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentAddcontMount); LIB_FUNCTION("D3H+cjfzzFY", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentAddcontShrink); LIB_FUNCTION("3rHWaV-1KC4", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentAddcontUnmount); LIB_FUNCTION("99b82IKXpH4", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentAppParamGetInt); LIB_FUNCTION("+OlXCu8qxUk", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentAppParamGetString); LIB_FUNCTION("gpGZDB4ZlrI", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentDownload0Expand); LIB_FUNCTION("S5eMvWnbbXg", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentDownload0Shrink); LIB_FUNCTION("B5gVeVurdUA", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentDownload1Expand); LIB_FUNCTION("kUeYucqnb7o", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentDownload1Shrink); LIB_FUNCTION("CN7EbEV7MFU", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentDownloadDataFormat); LIB_FUNCTION("Gl6w5i0JokY", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentDownloadDataGetAvailableSpaceKb); LIB_FUNCTION("5bvvbUSiFs4", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentGetAddcontDownloadProgress); LIB_FUNCTION("m47juOmH0VE", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentGetAddcontInfo); LIB_FUNCTION("xnd8BJzAxmk", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentGetAddcontInfoList); LIB_FUNCTION("XTWR0UXvcgs", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentGetEntitlementKey); LIB_FUNCTION("74-1x3lyZK8", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentGetRegion); LIB_FUNCTION("R9lA82OraNs", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentInitialize); LIB_FUNCTION("bVtF7v2uqT0", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentRequestPatchInstall); LIB_FUNCTION("9Gq5rOkWzNU", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentSmallSharedDataFormat); LIB_FUNCTION("xhb-r8etmAA", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentSmallSharedDataGetAvailableSpaceKb); LIB_FUNCTION("QuApZnMo9MM", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentSmallSharedDataMount); LIB_FUNCTION("EqMtBHWu-5M", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentSmallSharedDataUnmount); LIB_FUNCTION("a5N7lAG0y2Q", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentTemporaryDataFormat); LIB_FUNCTION("SaKib2Ug0yI", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentTemporaryDataGetAvailableSpaceKb); LIB_FUNCTION("7bOLX66Iz-U", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentTemporaryDataMount); LIB_FUNCTION("buYbeLOGWmA", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentTemporaryDataMount2); LIB_FUNCTION("bcolXMmp6qQ", "libSceAppContent", 1, "libSceAppContentUtil", 1, 1, sceAppContentTemporaryDataUnmount); LIB_FUNCTION("xmhnAoxN3Wk", "libSceAppContentPft", 1, "libSceAppContent", 1, 1, sceAppContentGetPftFlag); LIB_FUNCTION("xZo2-418Wdo", "libSceAppContentBundle", 1, "libSceAppContent", 1, 1, Func_C59A36FF8D7C59DA); LIB_FUNCTION("kJmjt81mXKQ", "libSceAppContentIro", 1, "libSceAppContent", 1, 1, sceAppContentAddcontEnqueueDownloadByEntitlementId); LIB_FUNCTION("efX3lrPwdKA", "libSceAppContentIro", 1, "libSceAppContent", 1, 1, sceAppContentAddcontMountByEntitlementId); LIB_FUNCTION("z9hgjLd1SGA", "libSceAppContentIro", 1, "libSceAppContent", 1, 1, sceAppContentGetAddcontInfoByEntitlementId); LIB_FUNCTION("3wUaDTGmjcQ", "libSceAppContentIro", 1, "libSceAppContent", 1, 1, sceAppContentGetAddcontInfoListByIroTag); LIB_FUNCTION("TCqT7kPuGx0", "libSceAppContentSc", 1, "libSceAppContent", 1, 1, sceAppContentGetDownloadedStoreCountry); }; } // namespace Libraries::AppContent
16,907
C++
.cpp
373
38.029491
100
0.682762
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,557
pngdec.cpp
shadps4-emu_shadPS4/src/core/libraries/libpng/pngdec.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/logging/log.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" #include "externals/stb_image.h" #include "pngdec.h" namespace Libraries::PngDec { void setImageInfoParams(OrbisPngDecImageInfo* imageInfo, int width, int height, int channels, bool isInterlaced, bool isTransparent) { if (imageInfo != nullptr) { imageInfo->imageWidth = width; imageInfo->imageHeight = height; imageInfo->bitDepth = 8; // always 8? switch (channels) { // clut missing case 1: imageInfo->colorSpace = OrbisPngDecColorSpace::ORBIS_PNG_DEC_COLOR_SPACE_GRAYSCALE; break; case 2: imageInfo->colorSpace = OrbisPngDecColorSpace::ORBIS_PNG_DEC_COLOR_SPACE_GRAYSCALE_ALPHA; break; case 3: imageInfo->colorSpace = OrbisPngDecColorSpace::ORBIS_PNG_DEC_COLOR_SPACE_RGB; break; case 4: imageInfo->colorSpace = OrbisPngDecColorSpace::ORBIS_PNG_DEC_COLOR_SPACE_RGBA; break; default: imageInfo->colorSpace = OrbisPngDecColorSpace::ORBIS_PNG_DEC_COLOR_SPACE_RGB; break; } imageInfo->imageFlag = 0; if (isInterlaced) { imageInfo->imageFlag |= ORBIS_PNG_DEC_IMAGE_FLAG_ADAM7_INTERLACE; } if (isTransparent) { imageInfo->imageFlag |= ORBIS_PNG_DEC_IMAGE_FLAG_TRNS_CHUNK_EXIST; } } } bool checktRNS(const u8* png_raw, int size) { for (int i = 30; i < size - 4; i += 4) { if (std::memcmp(png_raw + i, "tRNS", 4) == 0) { return true; } } return false; } s32 PS4_SYSV_ABI scePngDecCreate(const OrbisPngDecCreateParam* param, void* memoryAddress, u32 memorySize, OrbisPngDecHandle* handle) { if (param == nullptr || param->attribute > 1) { LOG_ERROR(Lib_Png, "Invalid param!"); return ORBIS_PNG_DEC_ERROR_INVALID_PARAM; } if (memoryAddress == nullptr) { LOG_ERROR(Lib_Png, "Invalid memory address!"); return ORBIS_PNG_DEC_ERROR_INVALID_ADDR; } if (param->maxImageWidth - 1 > 1000000) { LOG_ERROR(Lib_Png, "Invalid size! width = {}", param->maxImageWidth); return ORBIS_PNG_DEC_ERROR_INVALID_SIZE; } const OrbisPngDecCreateParam* nextParam = param + 1; int ret = (8 << (reinterpret_cast<uintptr_t>(nextParam) & 0x1f)) * (param->maxImageWidth + 0x47U & 0xfffffff8) + 0xd000; *handle = reinterpret_cast<OrbisPngDecHandle>(ret); return ORBIS_OK; } s32 PS4_SYSV_ABI scePngDecDecode(OrbisPngDecHandle handle, const OrbisPngDecDecodeParam* param, OrbisPngDecImageInfo* imageInfo) { if (handle == nullptr) { LOG_ERROR(Lib_Png, "invalid handle!"); return ORBIS_PNG_DEC_ERROR_INVALID_HANDLE; } if (param == nullptr) { LOG_ERROR(Lib_Png, "Invalid param!"); return ORBIS_PNG_DEC_ERROR_INVALID_PARAM; } if (param->pngMemAddr == nullptr || param->pngMemAddr == nullptr) { LOG_ERROR(Lib_Png, "invalid image address!"); return ORBIS_PNG_DEC_ERROR_INVALID_ADDR; } int width, height, channels; const u8* png_raw = (const u8*)param->pngMemAddr; u8* img = stbi_load_from_memory(png_raw, param->pngMemSize, &width, &height, &channels, STBI_rgb_alpha); // STBI_rgb_alpha? if (!img) { LOG_ERROR(Lib_Png, "Decoding failed!"); return ORBIS_PNG_DEC_ERROR_DECODE_ERROR; } bool isInterlaced = (png_raw[28] == 1); bool isTransparent = checktRNS(png_raw, param->pngMemSize); setImageInfoParams(imageInfo, width, height, channels, isInterlaced, isTransparent); u8* imageBuffer = (u8*)(param->imageMemAddr); memcpy(imageBuffer, img, width * height * 4); // copy/pass decoded data stbi_image_free(img); return 0; } s32 PS4_SYSV_ABI scePngDecDecodeWithInputControl() { LOG_ERROR(Lib_Png, "(STUBBED)called"); return ORBIS_OK; } s32 PS4_SYSV_ABI scePngDecDelete(OrbisPngDecHandle handle) { handle = nullptr; // ? LOG_ERROR(Lib_Png, "(STUBBED)called"); return ORBIS_OK; } s32 PS4_SYSV_ABI scePngDecParseHeader(const OrbisPngDecParseParam* param, OrbisPngDecImageInfo* imageInfo) { if (param == nullptr) { LOG_ERROR(Lib_Png, "Invalid param!"); return ORBIS_PNG_DEC_ERROR_INVALID_PARAM; } int width, height, channels; const u8* png_raw = (const u8*)(param->pngMemAddr); int img = stbi_info_from_memory(png_raw, param->pngMemSize, &width, &height, &channels); if (img == 0) { LOG_ERROR(Lib_Png, "Decoding failed!"); return ORBIS_PNG_DEC_ERROR_DECODE_ERROR; } bool isInterlaced = (png_raw[28] == 1); bool isTransparent = checktRNS(png_raw, param->pngMemSize); setImageInfoParams(imageInfo, width, height, channels, isInterlaced, isTransparent); return ORBIS_OK; } s32 PS4_SYSV_ABI scePngDecQueryMemorySize(const OrbisPngDecCreateParam* param) { if (param == nullptr) { LOG_ERROR(Lib_Png, "Invalid param!"); return ORBIS_PNG_DEC_ERROR_INVALID_PARAM; } if (param->attribute > 1) { LOG_ERROR(Lib_Png, "Invalid attribute! attribute = {}", param->attribute); return ORBIS_PNG_DEC_ERROR_INVALID_ADDR; } if (param->maxImageWidth - 1 > 1000000) { LOG_ERROR(Lib_Png, "Invalid size! width = {}", param->maxImageWidth); return ORBIS_PNG_DEC_ERROR_INVALID_SIZE; } int ret = (8 << ((u8)param->attribute & 0x1f)) * (param->maxImageWidth + 0x47U & 0xfffffff8) + 0xd090; return ret; } void RegisterlibScePngDec(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("m0uW+8pFyaw", "libScePngDec", 1, "libScePngDec", 1, 1, scePngDecCreate); LIB_FUNCTION("WC216DD3El4", "libScePngDec", 1, "libScePngDec", 1, 1, scePngDecDecode); LIB_FUNCTION("cJ--1xAbj-I", "libScePngDec", 1, "libScePngDec", 1, 1, scePngDecDecodeWithInputControl); LIB_FUNCTION("QbD+eENEwo8", "libScePngDec", 1, "libScePngDec", 1, 1, scePngDecDelete); LIB_FUNCTION("U6h4e5JRPaQ", "libScePngDec", 1, "libScePngDec", 1, 1, scePngDecParseHeader); LIB_FUNCTION("-6srIGbLTIU", "libScePngDec", 1, "libScePngDec", 1, 1, scePngDecQueryMemorySize); LIB_FUNCTION("cJ--1xAbj-I", "libScePngDec_jvm", 1, "libScePngDec", 1, 1, scePngDecDecodeWithInputControl); }; } // namespace Libraries::PngDec
6,706
C++
.cpp
156
35.538462
100
0.64301
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,558
savedata.cpp
shadps4-emu_shadPS4/src/core/libraries/save_data/savedata.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <span> #include <vector> #include <core/libraries/system/msgdialog_ui.h> #include <magic_enum.hpp> #include "common/assert.h" #include "common/cstring.h" #include "common/elf_info.h" #include "common/enum.h" #include "common/logging/log.h" #include "common/path_util.h" #include "common/string_util.h" #include "core/file_format/psf.h" #include "core/file_sys/fs.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" #include "core/libraries/save_data/savedata.h" #include "core/libraries/system/msgdialog.h" #include "save_backup.h" #include "save_instance.h" #include "save_memory.h" namespace fs = std::filesystem; namespace chrono = std::chrono; using Common::CString; using Common::ElfInfo; namespace Libraries::SaveData { enum class Error : u32 { OK = 0, USER_SERVICE_NOT_INITIALIZED = 0x80960002, PARAMETER = 0x809F0000, NOT_INITIALIZED = 0x809F0001, OUT_OF_MEMORY = 0x809F0002, BUSY = 0x809F0003, NOT_MOUNTED = 0x809F0004, EXISTS = 0x809F0007, NOT_FOUND = 0x809F0008, NO_SPACE_FS = 0x809F000A, INTERNAL = 0x809F000B, MOUNT_FULL = 0x809F000C, BAD_MOUNTED = 0x809F000D, BROKEN = 0x809F000F, INVALID_LOGIN_USER = 0x809F0011, MEMORY_NOT_READY = 0x809F0012, BACKUP_BUSY = 0x809F0013, BUSY_FOR_SAVING = 0x809F0016, }; enum class OrbisSaveDataSaveDataMemoryOption : u32 { NONE = 0, SET_PARAM = 1 << 0, DOUBLE_BUFFER = 1 << 1, UNLOCK_LIMITATIONS = 1 << 2, }; using OrbisUserServiceUserId = s32; using OrbisSaveDataBlocks = u64; constexpr u32 OrbisSaveDataBlockSize = 32768; // 32 KiB constexpr u32 OrbisSaveDataBlocksMin2 = 96; // 3MiB constexpr u32 OrbisSaveDataBlocksMax = 32768; // 1 GiB // Maximum size for a mount point "/savedataN", where N is a number constexpr size_t OrbisSaveDataMountPointDataMaxsize = 16; constexpr size_t OrbisSaveDataFingerprintDataSize = 65; // Maximum fingerprint size enum class OrbisSaveDataMountMode : u32 { RDONLY = 1 << 0, RDWR = 1 << 1, CREATE = 1 << 2, DESTRUCT_OFF = 1 << 3, COPY_ICON = 1 << 4, CREATE2 = 1 << 5, }; DECLARE_ENUM_FLAG_OPERATORS(OrbisSaveDataMountMode); enum class OrbisSaveDataMountStatus : u32 { NOTHING = 0, CREATED = 1, }; enum class OrbisSaveDataParamType : u32 { ALL = 0, TITLE = 1, SUB_TITLE = 2, DETAIL = 3, USER_PARAM = 4, MTIME = 5, }; enum class OrbisSaveDataSortKey : u32 { DIRNAME = 0, USER_PARAM = 1, BLOCKS = 2, MTIME = 3, FREE_BLOCKS = 5, }; enum class OrbisSaveDataSortOrder : u32 { ASCENT = 0, DESCENT = 1, }; struct OrbisSaveDataFingerprint { CString<OrbisSaveDataFingerprintDataSize> data; std::array<u8, 15> _pad; }; struct OrbisSaveDataBackup { OrbisUserServiceUserId userId; s32 : 32; const OrbisSaveDataTitleId* titleId; const OrbisSaveDataDirName* dirName; const OrbisSaveDataFingerprint* param; std::array<u8, 32> _reserved; }; struct OrbisSaveDataCheckBackupData { OrbisUserServiceUserId userId; s32 : 32; const OrbisSaveDataTitleId* titleId; const OrbisSaveDataDirName* dirName; OrbisSaveDataParam* param; OrbisSaveDataIcon* icon; std::array<u8, 32> _reserved; }; struct OrbisSaveDataDelete { OrbisUserServiceUserId userId; s32 : 32; const OrbisSaveDataTitleId* titleId; const OrbisSaveDataDirName* dirName; u32 _unused; std::array<u8, 32> _reserved; s32 : 32; }; struct OrbisSaveDataIcon { void* buf; size_t bufSize; size_t dataSize; std::array<u8, 32> _reserved; Error LoadIcon(const std::filesystem::path& icon_path) { try { const Common::FS::IOFile file(icon_path, Common::FS::FileAccessMode::Read); dataSize = file.GetSize(); file.Seek(0); file.ReadRaw<u8>(buf, std::min(bufSize, dataSize)); } catch (const fs::filesystem_error& e) { LOG_ERROR(Lib_SaveData, "Failed to load icon: {}", e.what()); return Error::INTERNAL; } return Error::OK; } }; struct OrbisSaveDataMemoryData { void* buf; size_t bufSize; s64 offset; u8 _reserved[40]; }; struct OrbisSaveDataMemoryGet2 { OrbisUserServiceUserId userId; std::array<u8, 4> _pad; OrbisSaveDataMemoryData* data; OrbisSaveDataParam* param; OrbisSaveDataIcon* icon; std::array<u8, 32> _reserved; }; struct OrbisSaveDataMemorySet2 { OrbisUserServiceUserId userId; std::array<u8, 4> _pad; const OrbisSaveDataMemoryData* data; const OrbisSaveDataParam* param; const OrbisSaveDataIcon* icon; std::array<u8, 32> _reserved; }; struct OrbisSaveDataMemorySetup2 { OrbisSaveDataSaveDataMemoryOption option; OrbisUserServiceUserId userId; size_t memorySize; size_t iconMemorySize; // +4.5 const OrbisSaveDataParam* initParam; // +4.5 const OrbisSaveDataIcon* initIcon; std::array<u8, 24> _reserved; }; struct OrbisSaveDataMemorySetupResult { size_t existedMemorySize; std::array<u8, 16> _reserved; }; struct OrbisSaveDataMemorySync { OrbisUserServiceUserId userId; std::array<u8, 36> _reserved; }; struct OrbisSaveDataMount2 { OrbisUserServiceUserId userId; s32 : 32; const OrbisSaveDataDirName* dirName; OrbisSaveDataBlocks blocks; OrbisSaveDataMountMode mountMode; std::array<u8, 32> _reserved; s32 : 32; }; struct OrbisSaveDataMount { OrbisUserServiceUserId userId; s32 : 32; const OrbisSaveDataTitleId* titleId; const OrbisSaveDataDirName* dirName; const OrbisSaveDataFingerprint* fingerprint; OrbisSaveDataBlocks blocks; OrbisSaveDataMountMode mountMode; std::array<u8, 32> _reserved; }; struct OrbisSaveDataMountInfo { OrbisSaveDataBlocks blocks; OrbisSaveDataBlocks freeBlocks; std::array<u8, 32> _reserved; }; struct OrbisSaveDataMountPoint { CString<OrbisSaveDataMountPointDataMaxsize> data; }; struct OrbisSaveDataMountResult { OrbisSaveDataMountPoint mount_point; OrbisSaveDataBlocks required_blocks; u32 _unused; // +4.5 OrbisSaveDataMountStatus mount_status; std::array<u8, 28> _reserved; s32 : 32; }; struct OrbisSaveDataRestoreBackupData { OrbisUserServiceUserId userId; s32 : 32; const OrbisSaveDataTitleId* titleId; const OrbisSaveDataDirName* dirName; const OrbisSaveDataFingerprint* fingerprint; u32 _unused; std::array<u8, 32> _reserved; s32 : 32; }; struct OrbisSaveDataTransferringMount { OrbisUserServiceUserId userId; const OrbisSaveDataTitleId* titleId; const OrbisSaveDataDirName* dirName; const OrbisSaveDataFingerprint* fingerprint; std::array<u8, 32> _reserved; }; struct OrbisSaveDataDirNameSearchCond { OrbisUserServiceUserId userId; int : 32; const OrbisSaveDataTitleId* titleId; const OrbisSaveDataDirName* dirName; OrbisSaveDataSortKey key; OrbisSaveDataSortOrder order; std::array<u8, 32> _reserved; }; struct OrbisSaveDataSearchInfo { u64 blocks; u64 freeBlocks; std::array<u8, 32> _reserved; }; struct OrbisSaveDataDirNameSearchResult { u32 hitNum; int : 32; OrbisSaveDataDirName* dirNames; u32 dirNamesNum; // +1.7 u32 setNum; // +1.7 OrbisSaveDataParam* params; // +2.5 OrbisSaveDataSearchInfo* infos; std::array<u8, 12> _reserved; int : 32; }; struct OrbisSaveDataEventParam { // dummy structure OrbisSaveDataEventParam() = delete; }; using OrbisSaveDataEventType = Backup::OrbisSaveDataEventType; struct OrbisSaveDataEvent { OrbisSaveDataEventType type; s32 errorCode; OrbisUserServiceUserId userId; std::array<u8, 4> _pad; OrbisSaveDataTitleId titleId; OrbisSaveDataDirName dirName; std::array<u8, 40> _reserved; }; static bool g_initialized = false; static std::string g_game_serial; static u32 g_fw_ver; static std::array<std::optional<SaveInstance>, 16> g_mount_slots; static void initialize() { g_initialized = true; g_game_serial = ElfInfo::Instance().GameSerial(); g_fw_ver = ElfInfo::Instance().FirmwareVer(); } // game_00other | game*other static bool match(std::string_view str, std::string_view pattern) { auto str_it = str.begin(); auto pat_it = pattern.begin(); while (str_it != str.end() && pat_it != pattern.end()) { if (*pat_it == '%') { // 0 or more wildcard for (auto str_wild_it = str_it; str_wild_it <= str.end(); ++str_wild_it) { if (match({str_wild_it, str.end()}, {pat_it + 1, pattern.end()})) { return true; } } return false; } if (*pat_it == '_') { // 1 character wildcard ++str_it; ++pat_it; } else if (*pat_it != *str_it) { return false; } ++str_it; ++pat_it; } return str_it == str.end() && pat_it == pattern.end(); } static Error setNotInitializedError() { if (g_fw_ver < ElfInfo::FW_20) { return Error::INTERNAL; } if (g_fw_ver < ElfInfo::FW_25) { return Error::USER_SERVICE_NOT_INITIALIZED; } return Error::NOT_INITIALIZED; } static Error saveDataMount(const OrbisSaveDataMount2* mount_info, OrbisSaveDataMountResult* mount_result, std::string_view title_id = g_game_serial) { if (mount_info->userId < 0) { return Error::INVALID_LOGIN_USER; } if (mount_info->dirName == nullptr) { LOG_INFO(Lib_SaveData, "called without dirName"); return Error::PARAMETER; } // check backup status { const auto save_path = SaveInstance::MakeDirSavePath(mount_info->userId, title_id, mount_info->dirName->data); if (Backup::IsBackupExecutingFor(save_path) && g_fw_ver) { return Error::BACKUP_BUSY; } } auto mount_mode = mount_info->mountMode; const bool is_ro = True(mount_mode & OrbisSaveDataMountMode::RDONLY); const bool create = True(mount_mode & OrbisSaveDataMountMode::CREATE); const bool create_if_not_exist = True(mount_mode & OrbisSaveDataMountMode::CREATE2) && g_fw_ver >= ElfInfo::FW_45; ASSERT(!create || !create_if_not_exist); // Can't have both const bool copy_icon = True(mount_mode & OrbisSaveDataMountMode::COPY_ICON); const bool ignore_corrupt = True(mount_mode & OrbisSaveDataMountMode::DESTRUCT_OFF) || g_fw_ver < ElfInfo::FW_16; const std::string_view dir_name{mount_info->dirName->data}; // find available mount point int slot_num = -1; for (size_t i = 0; i < g_mount_slots.size(); i++) { const auto& instance = g_mount_slots[i]; if (instance.has_value()) { const auto& slot_name = instance->GetDirName(); if (slot_name == dir_name) { return Error::BUSY; } } else { slot_num = static_cast<int>(i); break; } } if (slot_num == -1) { return Error::MOUNT_FULL; } SaveInstance save_instance{slot_num, mount_info->userId, std::string{title_id}, dir_name, (int)mount_info->blocks}; if (save_instance.Mounted()) { UNREACHABLE_MSG("Save instance should not be mounted"); } if (!create && !create_if_not_exist && !save_instance.Exists()) { return Error::NOT_FOUND; } if (create && save_instance.Exists()) { return Error::EXISTS; } bool to_be_created = !save_instance.Exists(); if (to_be_created) { // Check size if (mount_info->blocks < OrbisSaveDataBlocksMin2 || mount_info->blocks > OrbisSaveDataBlocksMax) { LOG_INFO(Lib_SaveData, "called with invalid block size"); } const auto root_save = Common::FS::GetUserPath(Common::FS::PathType::SaveDataDir); fs::create_directories(root_save); const auto available = fs::space(root_save).available; auto requested_size = save_instance.GetMaxBlocks() * OrbisSaveDataBlockSize; if (requested_size > available) { mount_result->required_blocks = (requested_size - available) / OrbisSaveDataBlockSize; return Error::NO_SPACE_FS; } } try { save_instance.SetupAndMount(is_ro, copy_icon, ignore_corrupt); } catch (const fs::filesystem_error& e) { if (e.code() == std::errc::illegal_byte_sequence) { LOG_ERROR(Lib_SaveData, "Corrupted save data"); return Error::BROKEN; } if (e.code() == std::errc::no_space_on_device) { return Error::NO_SPACE_FS; } LOG_ERROR(Lib_SaveData, "Failed to mount save data: {}", e.what()); return Error::INTERNAL; } mount_result->mount_point.data.FromString(save_instance.GetMountPoint()); if (g_fw_ver >= ElfInfo::FW_45) { mount_result->mount_status = create_if_not_exist && to_be_created ? OrbisSaveDataMountStatus::CREATED : OrbisSaveDataMountStatus::NOTHING; } g_mount_slots[slot_num].emplace(std::move(save_instance)); return Error::OK; } static Error Umount(const OrbisSaveDataMountPoint* mountPoint, bool call_backup = false) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (mountPoint == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "Umount mountPoint:{}", mountPoint->data.to_view()); const std::string_view mount_point_str{mountPoint->data}; for (auto& instance : g_mount_slots) { if (instance.has_value()) { const auto& slot_name = instance->GetMountPoint(); if (slot_name == mount_point_str) { // TODO: check if is busy instance->Umount(); if (call_backup) { Backup::StartThread(); Backup::NewRequest(instance->GetUserId(), instance->GetTitleId(), instance->GetDirName(), OrbisSaveDataEventType::UMOUNT_BACKUP); } instance.reset(); return Error::OK; } } } return Error::NOT_FOUND; } void OrbisSaveDataParam::FromSFO(const PSF& sfo) { memset(this, 0, sizeof(OrbisSaveDataParam)); title.FromString(sfo.GetString(SaveParams::MAINTITLE).value_or("Unknown")); subTitle.FromString(sfo.GetString(SaveParams::SUBTITLE).value_or("")); detail.FromString(sfo.GetString(SaveParams::DETAIL).value_or("")); userParam = sfo.GetInteger(SaveParams::SAVEDATA_LIST_PARAM).value_or(0); const auto time_since_epoch = sfo.GetLastWrite().time_since_epoch(); mtime = chrono::duration_cast<chrono::seconds>(time_since_epoch).count(); } void OrbisSaveDataParam::ToSFO(PSF& sfo) const { sfo.AddString(std::string{SaveParams::MAINTITLE}, std::string{title}, true); sfo.AddString(std::string{SaveParams::SUBTITLE}, std::string{subTitle}, true); sfo.AddString(std::string{SaveParams::DETAIL}, std::string{detail}, true); sfo.AddInteger(std::string{SaveParams::SAVEDATA_LIST_PARAM}, static_cast<s32>(userParam), true); } int PS4_SYSV_ABI sceSaveDataAbort() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataBackup(const OrbisSaveDataBackup* backup) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (backup == nullptr || backup->dirName == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } const std::string_view dir_name{backup->dirName->data}; LOG_DEBUG(Lib_SaveData, "called dirName: {}", dir_name); std::string_view title{backup->titleId != nullptr ? std::string_view{backup->titleId->data} : std::string_view{g_game_serial}}; for (const auto& instance : g_mount_slots) { if (instance.has_value() && instance->GetUserId() == backup->userId && instance->GetTitleId() == title && instance->GetDirName() == dir_name) { return Error::BUSY; } } Backup::StartThread(); Backup::NewRequest(backup->userId, title, dir_name, OrbisSaveDataEventType::BACKUP); return Error::OK; } int PS4_SYSV_ABI sceSaveDataBindPsnAccount() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataBindPsnAccountForSystemBackup() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataChangeDatabase() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataChangeInternal() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataCheckBackupData(const OrbisSaveDataCheckBackupData* check) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (check == nullptr || check->dirName == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } const std::string_view title{check->titleId != nullptr ? std::string_view{check->titleId->data} : std::string_view{g_game_serial}}; LOG_DEBUG(Lib_SaveData, "called with titleId={}", title); const auto save_path = SaveInstance::MakeDirSavePath(check->userId, title, check->dirName->data); for (const auto& instance : g_mount_slots) { if (instance.has_value() && instance->GetSavePath() == save_path) { return Error::BUSY; } } if (Backup::IsBackupExecutingFor(save_path)) { return Error::BACKUP_BUSY; } const auto backup_path = Backup::MakeBackupPath(save_path); if (!fs::exists(backup_path)) { return Error::NOT_FOUND; } if (check->param != nullptr) { PSF sfo; if (!sfo.Open(backup_path / "sce_sys" / "param.sfo")) { LOG_ERROR(Lib_SaveData, "Failed to read SFO at {}", fmt::UTF(backup_path.u8string())); return Error::INTERNAL; } check->param->FromSFO(sfo); } if (check->icon != nullptr) { const auto icon_path = backup_path / "sce_sys" / "icon0.png"; if (fs::exists(icon_path) && check->icon->LoadIcon(icon_path) != Error::OK) { return Error::INTERNAL; } } return Error::OK; } int PS4_SYSV_ABI sceSaveDataCheckBackupDataForCdlg() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataCheckBackupDataInternal() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataCheckCloudData() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataCheckIpmiIfSize() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataCheckSaveDataBroken() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataCheckSaveDataVersion() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataCheckSaveDataVersionLatest() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataClearProgress() { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } LOG_DEBUG(Lib_SaveData, "called"); Backup::ClearProgress(); return Error::OK; } int PS4_SYSV_ABI sceSaveDataCopy5() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataCreateUploadData() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataDebug() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataDebugCleanMount() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataDebugCompiledSdkVersion() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataDebugCreateSaveDataRoot() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataDebugGetThreadId() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataDebugRemoveSaveDataRoot() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataDebugTarget() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataDelete(const OrbisSaveDataDelete* del) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (del == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } const std::string_view dirName{del->dirName->data}; LOG_DEBUG(Lib_SaveData, "called dirName: {}", dirName); if (dirName.empty()) { return Error::PARAMETER; } for (const auto& instance : g_mount_slots) { if (instance.has_value() && instance->GetDirName() == dirName) { return Error::BUSY; } } const auto save_path = SaveInstance::MakeDirSavePath(del->userId, g_game_serial, dirName); try { if (fs::exists(save_path)) { fs::remove_all(save_path); } } catch (const fs::filesystem_error& e) { LOG_ERROR(Lib_SaveData, "Failed to delete save data: {}", e.what()); return Error::INTERNAL; } return Error::OK; } int PS4_SYSV_ABI sceSaveDataDelete5() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataDeleteAllUser() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataDeleteCloudData() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataDeleteUser() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataDirNameSearch(const OrbisSaveDataDirNameSearchCond* cond, OrbisSaveDataDirNameSearchResult* result) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (cond == nullptr || result == nullptr || cond->key > OrbisSaveDataSortKey::FREE_BLOCKS || cond->order > OrbisSaveDataSortOrder::DESCENT) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "called"); const std::string_view title_id{cond->titleId == nullptr ? std::string_view{g_game_serial} : std::string_view{cond->titleId->data}}; const auto save_path = SaveInstance::MakeTitleSavePath(cond->userId, title_id); if (!fs::exists(save_path)) { result->hitNum = 0; if (g_fw_ver >= ElfInfo::FW_17) { result->setNum = 0; } return Error::OK; } std::vector<std::string> dir_list; for (const auto& path : fs::directory_iterator{save_path}) { auto dir_name = path.path().filename().string(); // skip non-directories, sce_* and directories without param.sfo if (fs::is_directory(path) && !dir_name.starts_with("sce_") && fs::exists(SaveInstance::GetParamSFOPath(path))) { dir_list.push_back(dir_name); } } if (cond->dirName != nullptr) { // Filter names const auto pat = Common::ToLower(std::string_view{cond->dirName->data}); if (!pat.empty()) { std::erase_if(dir_list, [&](const std::string& dir_name) { return !match(Common::ToLower(dir_name), pat); }); } } std::unordered_map<std::string, PSF> map_dir_sfo; std::unordered_map<std::string, int> map_max_blocks; std::unordered_map<std::string, OrbisSaveDataBlocks> map_free_size; for (const auto& dir_name : dir_list) { const auto dir_path = SaveInstance::MakeDirSavePath(cond->userId, title_id, dir_name); const auto sfo_path = SaveInstance::GetParamSFOPath(dir_path); PSF sfo; if (!sfo.Open(sfo_path)) { LOG_ERROR(Lib_SaveData, "Failed to read SFO: {}", fmt::UTF(sfo_path.u8string())); ASSERT_MSG(false, "Failed to read SFO"); } size_t size = Common::FS::GetDirectorySize(dir_path); size_t total = SaveInstance::GetMaxBlockFromSFO(sfo); map_dir_sfo.emplace(dir_name, std::move(sfo)); map_free_size.emplace(dir_name, total - size / OrbisSaveDataBlockSize); map_max_blocks.emplace(dir_name, total); } #define PROJ(x) [&](const auto& v) { return x; } switch (cond->key) { case OrbisSaveDataSortKey::DIRNAME: std::ranges::stable_sort(dir_list); break; case OrbisSaveDataSortKey::USER_PARAM: std::ranges::stable_sort( dir_list, {}, PROJ(map_dir_sfo.at(v).GetInteger(SaveParams::SAVEDATA_LIST_PARAM).value_or(0))); break; case OrbisSaveDataSortKey::BLOCKS: std::ranges::stable_sort(dir_list, {}, PROJ(map_max_blocks.at(v))); break; case OrbisSaveDataSortKey::FREE_BLOCKS: std::ranges::stable_sort(dir_list, {}, PROJ(map_free_size.at(v))); break; case OrbisSaveDataSortKey::MTIME: std::ranges::stable_sort(dir_list, {}, PROJ(map_dir_sfo.at(v).GetLastWrite())); break; } #undef PROJ if (cond->order == OrbisSaveDataSortOrder::DESCENT) { std::ranges::reverse(dir_list); } size_t max_count = std::min(static_cast<size_t>(result->dirNamesNum), dir_list.size()); if (g_fw_ver >= ElfInfo::FW_17) { result->hitNum = dir_list.size(); result->setNum = max_count; } else { result->hitNum = max_count; } for (size_t i = 0; i < max_count; i++) { auto& name_data = result->dirNames[i].data; name_data.FromString(dir_list[i]); if (g_fw_ver >= ElfInfo::FW_17 && result->params != nullptr) { auto& sfo = map_dir_sfo.at(dir_list[i]); auto& param_data = result->params[i]; param_data.FromSFO(sfo); } if (g_fw_ver >= ElfInfo::FW_25 && result->infos != nullptr) { auto& info = result->infos[i]; info.blocks = map_max_blocks.at(dir_list[i]); info.freeBlocks = map_free_size.at(dir_list[i]); } } return Error::OK; } int PS4_SYSV_ABI sceSaveDataDirNameSearchInternal() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataDownload() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetAllSize() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetAppLaunchedUser() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetAutoUploadConditions() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetAutoUploadRequestInfo() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetAutoUploadSetting() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetBoundPsnAccountCount() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetClientThreadPriority() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetCloudQuotaInfo() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetDataBaseFilePath() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetEventInfo() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataGetEventResult(const OrbisSaveDataEventParam*, OrbisSaveDataEvent* event) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (event == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_TRACE(Lib_SaveData, "called"); auto last_event = Backup::PopLastEvent(); if (!last_event.has_value()) { return Error::NOT_FOUND; } event->type = last_event->origin; event->errorCode = 0; event->userId = last_event->user_id; event->titleId.data.FromString(last_event->title_id); event->dirName.data.FromString(last_event->dir_name); return Error::OK; } int PS4_SYSV_ABI sceSaveDataGetFormat() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetMountedSaveDataCount() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataGetMountInfo(const OrbisSaveDataMountPoint* mountPoint, OrbisSaveDataMountInfo* info) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (mountPoint == nullptr || info == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "called"); const std::string_view mount_point_str{mountPoint->data}; for (const auto& instance : g_mount_slots) { if (instance.has_value() && instance->GetMountPoint() == mount_point_str) { const u32 blocks = instance->GetMaxBlocks(); const u64 size = Common::FS::GetDirectorySize(instance->GetSavePath()); info->blocks = blocks; info->freeBlocks = blocks - size / OrbisSaveDataBlockSize; return Error::OK; } } return Error::NOT_MOUNTED; } Error PS4_SYSV_ABI sceSaveDataGetParam(const OrbisSaveDataMountPoint* mountPoint, OrbisSaveDataParamType paramType, void* paramBuf, size_t paramBufSize, size_t* gotSize) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (paramType > OrbisSaveDataParamType::MTIME || paramBuf == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "called: paramType = {}", magic_enum::enum_name(paramType)); const PSF* param_sfo = nullptr; const std::string_view mount_point_str{mountPoint->data}; for (const auto& instance : g_mount_slots) { if (instance.has_value() && instance->GetMountPoint() == mount_point_str) { param_sfo = &instance->GetParamSFO(); break; } } if (param_sfo == nullptr) { return Error::NOT_MOUNTED; } switch (paramType) { case OrbisSaveDataParamType::ALL: { const auto param = static_cast<OrbisSaveDataParam*>(paramBuf); ASSERT(paramBufSize == sizeof(OrbisSaveDataParam)); param->FromSFO(*param_sfo); if (gotSize != nullptr) { *gotSize = sizeof(OrbisSaveDataParam); } break; } case OrbisSaveDataParamType::TITLE: case OrbisSaveDataParamType::SUB_TITLE: case OrbisSaveDataParamType::DETAIL: { const auto param = static_cast<char*>(paramBuf); std::string_view key; if (paramType == OrbisSaveDataParamType::TITLE) { key = SaveParams::MAINTITLE; } else if (paramType == OrbisSaveDataParamType::SUB_TITLE) { key = SaveParams::SUBTITLE; } else if (paramType == OrbisSaveDataParamType::DETAIL) { key = SaveParams::DETAIL; } else { UNREACHABLE(); } const size_t s = param_sfo->GetString(key).value_or("").copy(param, paramBufSize - 1); param[s] = '\0'; // null terminate if (gotSize != nullptr) { *gotSize = s + 1; } } break; case OrbisSaveDataParamType::USER_PARAM: { const auto param = static_cast<u32*>(paramBuf); *param = param_sfo->GetInteger(SaveParams::SAVEDATA_LIST_PARAM).value_or(0); if (gotSize != nullptr) { *gotSize = sizeof(u32); } } break; case OrbisSaveDataParamType::MTIME: { const auto param = static_cast<time_t*>(paramBuf); const auto last_write = param_sfo->GetLastWrite().time_since_epoch(); *param = chrono::duration_cast<chrono::seconds>(last_write).count(); if (gotSize != nullptr) { *gotSize = sizeof(time_t); } } break; default: UNREACHABLE(); } return Error::OK; } Error PS4_SYSV_ABI sceSaveDataGetProgress(float* progress) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (progress == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "called"); *progress = Backup::GetProgress(); return Error::OK; } int PS4_SYSV_ABI sceSaveDataGetSaveDataCount() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataGetSaveDataMemory(const OrbisUserServiceUserId userId, void* buf, const size_t bufSize, const int64_t offset) { LOG_DEBUG(Lib_SaveData, "Redirecting to sceSaveDataGetSaveDataMemory2"); OrbisSaveDataMemoryData data{}; data.buf = buf; data.bufSize = bufSize; data.offset = offset; OrbisSaveDataMemoryGet2 param{}; param.userId = userId; param.data = &data; param.param = nullptr; param.icon = nullptr; return sceSaveDataGetSaveDataMemory2(&param); } Error PS4_SYSV_ABI sceSaveDataGetSaveDataMemory2(OrbisSaveDataMemoryGet2* getParam) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (getParam == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } if (!SaveMemory::IsSaveMemoryInitialized()) { LOG_INFO(Lib_SaveData, "called without save memory initialized"); return Error::MEMORY_NOT_READY; } if (SaveMemory::IsSaving()) { LOG_TRACE(Lib_SaveData, "called while saving"); return Error::BUSY_FOR_SAVING; } LOG_DEBUG(Lib_SaveData, "called"); auto data = getParam->data; if (data != nullptr) { SaveMemory::ReadMemory(data->buf, data->bufSize, data->offset); } auto param = getParam->param; if (param != nullptr) { param->FromSFO(SaveMemory::GetParamSFO()); } auto icon = getParam->icon; if (icon != nullptr) { auto icon_mem = SaveMemory::GetIcon(); size_t total = std::min(icon->bufSize, icon_mem.size()); std::memcpy(icon->buf, icon_mem.data(), total); icon->dataSize = total; } return Error::OK; } int PS4_SYSV_ABI sceSaveDataGetSaveDataRootDir() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetSaveDataRootPath() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetSaveDataRootUsbPath() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetSavePoint() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataGetUpdatedDataCount() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataInitialize(void*) { LOG_DEBUG(Lib_SaveData, "called"); initialize(); return Error::OK; } Error PS4_SYSV_ABI sceSaveDataInitialize2(void*) { LOG_DEBUG(Lib_SaveData, "called"); initialize(); return Error::OK; } Error PS4_SYSV_ABI sceSaveDataInitialize3(void*) { LOG_DEBUG(Lib_SaveData, "called"); initialize(); return Error::OK; } int PS4_SYSV_ABI sceSaveDataInitializeForCdlg() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataIsDeletingUsbDb() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataIsMounted() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataLoadIcon(const OrbisSaveDataMountPoint* mountPoint, OrbisSaveDataIcon* icon) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (mountPoint == nullptr || icon == nullptr || icon->buf == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "called"); std::filesystem::path path; const std::string_view mount_point_str{mountPoint->data}; for (const auto& instance : g_mount_slots) { if (instance.has_value() && instance->GetMountPoint() == mount_point_str) { path = instance->GetIconPath(); break; } } if (path.empty()) { return Error::NOT_MOUNTED; } if (!fs::exists(path)) { return Error::NOT_FOUND; } return icon->LoadIcon(path); } Error PS4_SYSV_ABI sceSaveDataMount(const OrbisSaveDataMount* mount, OrbisSaveDataMountResult* mount_result) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (mount == nullptr && mount->dirName != nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "called dirName: {}, mode: {:0b}, blocks: {}", mount->dirName->data.to_view(), (int)mount->mountMode, mount->blocks); OrbisSaveDataMount2 mount_info{}; mount_info.userId = mount->userId; mount_info.dirName = mount->dirName; mount_info.mountMode = mount->mountMode; mount_info.blocks = mount->blocks; return saveDataMount(&mount_info, mount_result); } Error PS4_SYSV_ABI sceSaveDataMount2(const OrbisSaveDataMount2* mount, OrbisSaveDataMountResult* mount_result) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (mount == nullptr && mount->dirName != nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "called dirName: {}, mode: {:0b}, blocks: {}", mount->dirName->data.to_view(), (int)mount->mountMode, mount->blocks); return saveDataMount(mount, mount_result); } int PS4_SYSV_ABI sceSaveDataMount5() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataMountInternal() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataMountSys() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataPromote5() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataRebuildDatabase() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataRegisterEventCallback() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataRestoreBackupData(const OrbisSaveDataRestoreBackupData* restore) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (restore == nullptr || restore->dirName == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } const std::string_view dir_name{restore->dirName->data}; LOG_DEBUG(Lib_SaveData, "called dirName: {}", dir_name); std::string_view title{restore->titleId != nullptr ? std::string_view{restore->titleId->data} : std::string_view{g_game_serial}}; const auto save_path = SaveInstance::MakeDirSavePath(restore->userId, title, dir_name); for (const auto& instance : g_mount_slots) { if (instance.has_value() && instance->GetSavePath() == save_path) { return Error::BUSY; } } if (Backup::IsBackupExecutingFor(save_path)) { return Error::BACKUP_BUSY; } const auto backup_path = Backup::MakeBackupPath(save_path); if (!fs::exists(backup_path)) { return Error::NOT_FOUND; } const bool ok = Backup::Restore(save_path); if (!ok) { return Error::INTERNAL; } return Error::OK; } int PS4_SYSV_ABI sceSaveDataRestoreBackupDataForCdlg() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataRestoreLoadSaveDataMemory() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataSaveIcon(const OrbisSaveDataMountPoint* mountPoint, const OrbisSaveDataIcon* icon) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (mountPoint == nullptr || icon == nullptr || icon->buf == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "called"); std::filesystem::path path; const std::string_view mount_point_str{mountPoint->data}; for (const auto& instance : g_mount_slots) { if (instance.has_value() && instance->GetMountPoint() == mount_point_str) { if (instance->IsReadOnly()) { return Error::BAD_MOUNTED; } path = instance->GetIconPath(); break; } } if (path.empty()) { return Error::NOT_MOUNTED; } try { const Common::FS::IOFile file(path, Common::FS::FileAccessMode::Write); file.WriteRaw<u8>(icon->buf, std::min(icon->bufSize, icon->dataSize)); } catch (const fs::filesystem_error& e) { LOG_ERROR(Lib_SaveData, "Failed to load icon: {}", e.what()); return Error::INTERNAL; } return Error::OK; } int PS4_SYSV_ABI sceSaveDataSetAutoUploadSetting() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataSetEventInfo() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataSetParam(const OrbisSaveDataMountPoint* mountPoint, OrbisSaveDataParamType paramType, const void* paramBuf, size_t paramBufSize) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (paramType > OrbisSaveDataParamType::USER_PARAM || mountPoint == nullptr || paramBuf == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "called: paramType = {}", magic_enum::enum_name(paramType)); PSF* param_sfo = nullptr; const std::string_view mount_point_str{mountPoint->data}; for (auto& instance : g_mount_slots) { if (instance.has_value() && instance->GetMountPoint() == mount_point_str) { param_sfo = &instance->GetParamSFO(); break; } } if (param_sfo == nullptr) { return Error::NOT_MOUNTED; } switch (paramType) { case OrbisSaveDataParamType::ALL: { const auto param = static_cast<const OrbisSaveDataParam*>(paramBuf); ASSERT(paramBufSize == sizeof(OrbisSaveDataParam)); param->ToSFO(*param_sfo); return Error::OK; } break; case OrbisSaveDataParamType::TITLE: { const auto value = static_cast<const char*>(paramBuf); param_sfo->AddString(std::string{SaveParams::MAINTITLE}, {value}, true); } break; case OrbisSaveDataParamType::SUB_TITLE: { const auto value = static_cast<const char*>(paramBuf); param_sfo->AddString(std::string{SaveParams::SUBTITLE}, {value}, true); } break; case OrbisSaveDataParamType::DETAIL: { const auto value = static_cast<const char*>(paramBuf); param_sfo->AddString(std::string{SaveParams::DETAIL}, {value}, true); } break; case OrbisSaveDataParamType::USER_PARAM: { const auto value = static_cast<const s32*>(paramBuf); param_sfo->AddInteger(std::string{SaveParams::SAVEDATA_LIST_PARAM}, *value, true); } break; default: UNREACHABLE(); } return Error::OK; } int PS4_SYSV_ABI sceSaveDataSetSaveDataLibraryUser() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataSetSaveDataMemory(OrbisUserServiceUserId userId, void* buf, size_t bufSize, int64_t offset) { LOG_DEBUG(Lib_SaveData, "Redirecting to sceSaveDataSetSaveDataMemory2"); OrbisSaveDataMemoryData data{}; data.buf = buf; data.bufSize = bufSize; data.offset = offset; OrbisSaveDataMemorySet2 setParam{}; setParam.userId = userId; setParam.data = &data; setParam.param = nullptr; setParam.icon = nullptr; return sceSaveDataSetSaveDataMemory2(&setParam); } Error PS4_SYSV_ABI sceSaveDataSetSaveDataMemory2(const OrbisSaveDataMemorySet2* setParam) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (setParam == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } if (!SaveMemory::IsSaveMemoryInitialized()) { LOG_INFO(Lib_SaveData, "called without save memory initialized"); return Error::MEMORY_NOT_READY; } if (SaveMemory::IsSaving()) { LOG_TRACE(Lib_SaveData, "called while saving"); return Error::BUSY_FOR_SAVING; } LOG_DEBUG(Lib_SaveData, "called"); auto data = setParam->data; if (data != nullptr) { SaveMemory::WriteMemory(data->buf, data->bufSize, data->offset); } auto param = setParam->param; if (param != nullptr) { param->ToSFO(SaveMemory::GetParamSFO()); SaveMemory::SaveSFO(); } auto icon = setParam->icon; if (icon != nullptr) { SaveMemory::WriteIcon(icon->buf, icon->bufSize); } SaveMemory::TriggerSaveWithoutEvent(); return Error::OK; } Error PS4_SYSV_ABI sceSaveDataSetupSaveDataMemory(OrbisUserServiceUserId userId, size_t memorySize, OrbisSaveDataParam* param) { LOG_DEBUG(Lib_SaveData, "called: userId = {}, memorySize = {}", userId, memorySize); OrbisSaveDataMemorySetup2 setupParam{}; setupParam.userId = userId; setupParam.memorySize = memorySize; setupParam.initParam = nullptr; setupParam.initIcon = nullptr; OrbisSaveDataMemorySetupResult result{}; const auto res = sceSaveDataSetupSaveDataMemory2(&setupParam, &result); if (res != Error::OK) { return res; } if (param != nullptr) { OrbisSaveDataMemorySet2 setParam{}; setParam.userId = userId; setParam.data = nullptr; setParam.param = param; setParam.icon = nullptr; sceSaveDataSetSaveDataMemory2(&setParam); } return Error::OK; } Error PS4_SYSV_ABI sceSaveDataSetupSaveDataMemory2(const OrbisSaveDataMemorySetup2* setupParam, OrbisSaveDataMemorySetupResult* result) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (setupParam == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "called"); SaveMemory::SetDirectories(setupParam->userId, g_game_serial); const auto& save_path = SaveMemory::GetSavePath(); for (const auto& instance : g_mount_slots) { if (instance.has_value() && instance->GetSavePath() == save_path) { return Error::BUSY; } } try { size_t existed_size = SaveMemory::CreateSaveMemory(setupParam->memorySize); if (existed_size == 0) { // Just created if (g_fw_ver >= ElfInfo::FW_45 && setupParam->initParam != nullptr) { auto& sfo = SaveMemory::GetParamSFO(); setupParam->initParam->ToSFO(sfo); } SaveMemory::SaveSFO(); auto init_icon = setupParam->initIcon; if (g_fw_ver >= ElfInfo::FW_45 && init_icon != nullptr) { SaveMemory::SetIcon(init_icon->buf, init_icon->bufSize); } else { SaveMemory::SetIcon(nullptr, 0); } } SaveMemory::TriggerSaveWithoutEvent(); if (g_fw_ver >= ElfInfo::FW_45 && result != nullptr) { result->existedMemorySize = existed_size; } } catch (const fs::filesystem_error& e) { LOG_ERROR(Lib_SaveData, "Failed to create/load save memory: {}", e.what()); const MsgDialog::MsgDialogState dialog{MsgDialog::MsgDialogState::UserState{ .type = MsgDialog::ButtonType::OK, .msg = "Failed to create or load save memory:\n" + std::string{e.what()}, }}; MsgDialog::ShowMsgDialog(dialog); return Error::INTERNAL; } return Error::OK; } int PS4_SYSV_ABI sceSaveDataShutdownStart() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataSupportedFakeBrokenStatus() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataSyncCloudList() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataSyncSaveDataMemory(OrbisSaveDataMemorySync* syncParam) { if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (syncParam == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } if (!SaveMemory::IsSaveMemoryInitialized()) { LOG_INFO(Lib_SaveData, "called without save memory initialized"); return Error::MEMORY_NOT_READY; } LOG_DEBUG(Lib_SaveData, "called"); bool ok = SaveMemory::TriggerSave(); if (!ok) { return Error::BUSY_FOR_SAVING; } return Error::OK; } Error PS4_SYSV_ABI sceSaveDataTerminate() { LOG_DEBUG(Lib_SaveData, "called"); if (!g_initialized) { return setNotInitializedError(); } for (auto& instance : g_mount_slots) { if (instance.has_value()) { if (g_fw_ver >= ElfInfo::FW_40) { return Error::BUSY; } instance->Umount(); instance.reset(); } } g_initialized = false; Backup::StopThread(); return Error::OK; } Error PS4_SYSV_ABI sceSaveDataTransferringMount(const OrbisSaveDataTransferringMount* mount, OrbisSaveDataMountResult* mountResult) { LOG_DEBUG(Lib_SaveData, "called"); if (!g_initialized) { LOG_INFO(Lib_SaveData, "called without initialize"); return setNotInitializedError(); } if (mount == nullptr || mount->titleId == nullptr || mount->dirName == nullptr) { LOG_INFO(Lib_SaveData, "called with invalid parameter"); return Error::PARAMETER; } LOG_DEBUG(Lib_SaveData, "called titleId: {}, dirName: {}", mount->titleId->data.to_view(), mount->dirName->data.to_view()); OrbisSaveDataMount2 mount_info{}; mount_info.userId = mount->userId; mount_info.dirName = mount->dirName; mount_info.mountMode = OrbisSaveDataMountMode::RDONLY; return saveDataMount(&mount_info, mountResult, mount->titleId->data.to_string()); } Error PS4_SYSV_ABI sceSaveDataUmount(const OrbisSaveDataMountPoint* mountPoint) { LOG_DEBUG(Lib_SaveData, "called"); return Umount(mountPoint); } int PS4_SYSV_ABI sceSaveDataUmountSys() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } Error PS4_SYSV_ABI sceSaveDataUmountWithBackup(const OrbisSaveDataMountPoint* mountPoint) { LOG_DEBUG(Lib_SaveData, "called"); return Umount(mountPoint, true); } int PS4_SYSV_ABI sceSaveDataUnregisterEventCallback() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSaveDataUpload() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_02E4C4D201716422() { LOG_ERROR(Lib_SaveData, "(STUBBED) called"); return ORBIS_OK; } void RegisterlibSceSaveData(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("dQ2GohUHXzk", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataAbort); LIB_FUNCTION("z1JA8-iJt3k", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataBackup); LIB_FUNCTION("kLJQ3XioYiU", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataBindPsnAccount); LIB_FUNCTION("hHHCPRqA3+g", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataBindPsnAccountForSystemBackup); LIB_FUNCTION("ykwIZfVD08s", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataChangeDatabase); LIB_FUNCTION("G0hFeOdRCUs", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataChangeInternal); LIB_FUNCTION("RQOqDbk3bSU", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataCheckBackupData); LIB_FUNCTION("rYvLW1z2poM", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataCheckBackupDataForCdlg); LIB_FUNCTION("v1TrX+3ZB10", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataCheckBackupDataInternal); LIB_FUNCTION("-eczr5e4dsI", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataCheckCloudData); LIB_FUNCTION("4OPOZxfVkHA", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataCheckIpmiIfSize); LIB_FUNCTION("1i0rfc+mfa8", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataCheckSaveDataBroken); LIB_FUNCTION("p6A1adyQi3E", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataCheckSaveDataVersion); LIB_FUNCTION("S49B+I96kpk", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataCheckSaveDataVersionLatest); LIB_FUNCTION("Wz-4JZfeO9g", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataClearProgress); LIB_FUNCTION("YbCO38BOOl4", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataCopy5); LIB_FUNCTION("kbIIP9aXK9A", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataCreateUploadData); LIB_FUNCTION("gW6G4HxBBXA", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDebug); LIB_FUNCTION("bYCnxLexU7M", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDebugCleanMount); LIB_FUNCTION("hVDqYB8+jkk", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDebugCompiledSdkVersion); LIB_FUNCTION("K9gXXlrVLNI", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDebugCreateSaveDataRoot); LIB_FUNCTION("5yHFvMwZX2o", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDebugGetThreadId); LIB_FUNCTION("UGTldPVEdB4", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDebugRemoveSaveDataRoot); LIB_FUNCTION("AYBQmnRplrg", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDebugTarget); LIB_FUNCTION("S1GkePI17zQ", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDelete); LIB_FUNCTION("SQWusLoK8Pw", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDelete5); LIB_FUNCTION("pJrlpCgR8h4", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDeleteAllUser); LIB_FUNCTION("fU43mJUgKcM", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDeleteCloudData); LIB_FUNCTION("uZqc4JpFdeY", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDeleteUser); LIB_FUNCTION("dyIhnXq-0SM", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDirNameSearch); LIB_FUNCTION("xJ5NFWC3m+k", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDirNameSearchInternal); LIB_FUNCTION("h1nP9EYv3uc", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataDownload); LIB_FUNCTION("A1ThglSGUwA", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetAllSize); LIB_FUNCTION("KuXcrMAQIMQ", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetAppLaunchedUser); LIB_FUNCTION("itZ46iH14Vs", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetAutoUploadConditions); LIB_FUNCTION("PL20kjAXZZ4", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetAutoUploadRequestInfo); LIB_FUNCTION("G12foE0S77E", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetAutoUploadSetting); LIB_FUNCTION("PzDtD6eBXIM", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetBoundPsnAccountCount); LIB_FUNCTION("tu0SDPl+h88", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetClientThreadPriority); LIB_FUNCTION("6lZYZqQPfkY", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetCloudQuotaInfo); LIB_FUNCTION("CWlBd2Ay1M4", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetDataBaseFilePath); LIB_FUNCTION("eBSSNIG6hMk", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetEventInfo); LIB_FUNCTION("j8xKtiFj0SY", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetEventResult); LIB_FUNCTION("UMpxor4AlKQ", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetFormat); LIB_FUNCTION("pc4guaUPVqA", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetMountedSaveDataCount); LIB_FUNCTION("65VH0Qaaz6s", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetMountInfo); LIB_FUNCTION("XgvSuIdnMlw", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetParam); LIB_FUNCTION("ANmSWUiyyGQ", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetProgress); LIB_FUNCTION("SN7rTPHS+Cg", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetSaveDataCount); LIB_FUNCTION("7Bt5pBC-Aco", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetSaveDataMemory); LIB_FUNCTION("QwOO7vegnV8", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetSaveDataMemory2); LIB_FUNCTION("+bRDRotfj0Y", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetSaveDataRootDir); LIB_FUNCTION("3luF0xq0DkQ", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetSaveDataRootPath); LIB_FUNCTION("DwAvlQGvf1o", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetSaveDataRootUsbPath); LIB_FUNCTION("kb24-4DLyNo", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetSavePoint); LIB_FUNCTION("OYmnApJ9q+U", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataGetUpdatedDataCount); LIB_FUNCTION("ZkZhskCPXFw", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataInitialize); LIB_FUNCTION("l1NmDeDpNGU", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataInitialize2); LIB_FUNCTION("TywrFKCoLGY", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataInitialize3); LIB_FUNCTION("g9uwUI3BlQ8", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataInitializeForCdlg); LIB_FUNCTION("voAQW45oKuo", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataIsDeletingUsbDb); LIB_FUNCTION("ieP6jP138Qo", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataIsMounted); LIB_FUNCTION("cGjO3wM3V28", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataLoadIcon); LIB_FUNCTION("32HQAQdwM2o", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataMount); LIB_FUNCTION("0z45PIH+SNI", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataMount2); LIB_FUNCTION("xz0YMi6BfNk", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataMount5); LIB_FUNCTION("msCER7Iibm8", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataMountInternal); LIB_FUNCTION("-XYmdxjOqyA", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataMountSys); LIB_FUNCTION("uNu7j3pL2mQ", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataPromote5); LIB_FUNCTION("SgIY-XYA2Xg", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataRebuildDatabase); LIB_FUNCTION("hsKd5c21sQc", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataRegisterEventCallback); LIB_FUNCTION("lU9YRFsgwSU", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataRestoreBackupData); LIB_FUNCTION("HuToUt1GQ8w", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataRestoreBackupDataForCdlg); LIB_FUNCTION("aoZKKNjlq3Y", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataRestoreLoadSaveDataMemory); LIB_FUNCTION("c88Yy54Mx0w", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSaveIcon); LIB_FUNCTION("0VFHv-Fa4w8", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSetAutoUploadSetting); LIB_FUNCTION("52pL2GKkdjA", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSetEventInfo); LIB_FUNCTION("85zul--eGXs", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSetParam); LIB_FUNCTION("v3vg2+cooYw", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSetSaveDataLibraryUser); LIB_FUNCTION("h3YURzXGSVQ", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSetSaveDataMemory); LIB_FUNCTION("cduy9v4YmT4", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSetSaveDataMemory2); LIB_FUNCTION("v7AAAMo0Lz4", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSetupSaveDataMemory); LIB_FUNCTION("oQySEUfgXRA", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSetupSaveDataMemory2); LIB_FUNCTION("zMgXM79jRhw", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataShutdownStart); LIB_FUNCTION("+orZm32HB1s", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSupportedFakeBrokenStatus); LIB_FUNCTION("LMSQUTxmGVg", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSyncCloudList); LIB_FUNCTION("wiT9jeC7xPw", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataSyncSaveDataMemory); LIB_FUNCTION("yKDy8S5yLA0", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataTerminate); LIB_FUNCTION("WAzWTZm1H+I", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataTransferringMount); LIB_FUNCTION("BMR4F-Uek3E", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataUmount); LIB_FUNCTION("2-8NWLS8QSA", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataUmountSys); LIB_FUNCTION("VwadwBBBJ80", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataUmountWithBackup); LIB_FUNCTION("v-AK1AxQhS0", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataUnregisterEventCallback); LIB_FUNCTION("COwz3WBj+5s", "libSceSaveData", 1, "libSceSaveData", 1, 1, sceSaveDataUpload); LIB_FUNCTION("AuTE0gFxZCI", "libSceSaveData", 1, "libSceSaveData", 1, 1, Func_02E4C4D201716422); }; } // namespace Libraries::SaveData
65,721
C++
.cpp
1,653
32.851785
100
0.654157
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,559
save_instance.cpp
shadps4-emu_shadPS4/src/core/libraries/save_data/save_instance.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <iostream> #include <magic_enum.hpp> #include "common/assert.h" #include "common/config.h" #include "common/path_util.h" #include "common/singleton.h" #include "core/file_sys/fs.h" #include "save_instance.h" constexpr auto OrbisSaveDataBlocksMin2 = 96; // 3MiB constexpr auto OrbisSaveDataBlocksMax = 32768; // 1 GiB constexpr std::string_view sce_sys = "sce_sys"; // system folder inside save static Core::FileSys::MntPoints* g_mnt = Common::Singleton<Core::FileSys::MntPoints>::Instance(); namespace fs = std::filesystem; // clang-format off static const std::unordered_map<std::string, std::string> default_title = { {"ja_JP", "セーブデータ"}, {"en", "Saved Data"}, {"fr", "Données sauvegardées"}, {"es_ES", "Datos guardados"}, {"de", "Gespeicherte Daten"}, {"it", "Dati salvati"}, {"nl", "Opgeslagen data"}, {"pt_PT", "Dados guardados"}, {"ru", "Сохраненные данные"}, {"ko_KR", "저장 데이터"}, {"zh_CN", "保存数据"}, {"fi", "Tallennetut tiedot"}, {"sv_SE", "Sparade data"}, {"da_DK", "Gemte data"}, {"no_NO", "Lagrede data"}, {"pl_PL", "Zapisane dane"}, {"pt_BR", "Dados salvos"}, {"tr_TR", "Kayıtlı Veriler"}, }; // clang-format on namespace Libraries::SaveData { std::filesystem::path SaveInstance::MakeTitleSavePath(OrbisUserServiceUserId user_id, std::string_view game_serial) { return Common::FS::GetUserPath(Common::FS::PathType::SaveDataDir) / std::to_string(user_id) / game_serial; } std::filesystem::path SaveInstance::MakeDirSavePath(OrbisUserServiceUserId user_id, std::string_view game_serial, std::string_view dir_name) { return Common::FS::GetUserPath(Common::FS::PathType::SaveDataDir) / std::to_string(user_id) / game_serial / dir_name; } uint64_t SaveInstance::GetMaxBlockFromSFO(const PSF& psf) { const auto vec = psf.GetBinary(std::string{SaveParams::SAVEDATA_BLOCKS}); if (!vec.has_value()) { return OrbisSaveDataBlocksMax; } auto value = vec.value(); return *(uint64_t*)value.data(); } std::filesystem::path SaveInstance::GetParamSFOPath(const std::filesystem::path& dir_path) { return dir_path / sce_sys / "param.sfo"; } void SaveInstance::SetupDefaultParamSFO(PSF& param_sfo, std::string dir_name, std::string game_serial) { std::string locale = Config::getEmulatorLanguage(); if (!default_title.contains(locale)) { locale = "en"; } #define P(type, key, ...) param_sfo.Add##type(std::string{key}, __VA_ARGS__) // TODO Link with user service P(Binary, SaveParams::ACCOUNT_ID, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); P(String, SaveParams::MAINTITLE, default_title.at(locale)); P(String, SaveParams::SUBTITLE, ""); P(String, SaveParams::DETAIL, ""); P(String, SaveParams::SAVEDATA_DIRECTORY, std::move(dir_name)); P(Integer, SaveParams::SAVEDATA_LIST_PARAM, 0); P(String, SaveParams::TITLE_ID, std::move(game_serial)); P(Binary, SaveParams::SAVEDATA_BLOCKS, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); #undef P } SaveInstance::SaveInstance(int slot_num, OrbisUserServiceUserId user_id, std::string _game_serial, std::string_view _dir_name, int max_blocks) : slot_num(slot_num), user_id(user_id), game_serial(std::move(_game_serial)), dir_name(_dir_name), max_blocks(std::clamp(max_blocks, OrbisSaveDataBlocksMin2, OrbisSaveDataBlocksMax)) { ASSERT(slot_num >= 0 && slot_num < 16); save_path = MakeDirSavePath(user_id, game_serial, dir_name); const auto sce_sys_path = save_path / sce_sys; param_sfo_path = sce_sys_path / "param.sfo"; corrupt_file_path = sce_sys_path / "corrupted"; mount_point = "/savedata" + std::to_string(slot_num); this->exists = fs::exists(param_sfo_path); this->mounted = g_mnt->GetMount(mount_point) != nullptr; } SaveInstance::~SaveInstance() { if (mounted) { Umount(); } } SaveInstance::SaveInstance(SaveInstance&& other) noexcept { if (this == &other) return; *this = std::move(other); } SaveInstance& SaveInstance::operator=(SaveInstance&& other) noexcept { if (this == &other) return *this; slot_num = other.slot_num; user_id = other.user_id; game_serial = std::move(other.game_serial); dir_name = std::move(other.dir_name); save_path = std::move(other.save_path); param_sfo_path = std::move(other.param_sfo_path); corrupt_file_path = std::move(other.corrupt_file_path); corrupt_file = std::move(other.corrupt_file); param_sfo = std::move(other.param_sfo); mount_point = std::move(other.mount_point); max_blocks = other.max_blocks; exists = other.exists; mounted = other.mounted; read_only = other.read_only; other.mounted = false; return *this; } void SaveInstance::SetupAndMount(bool read_only, bool copy_icon, bool ignore_corrupt) { if (mounted) { UNREACHABLE_MSG("Save instance is already mounted"); } this->exists = fs::exists(param_sfo_path); // check again just in case if (!exists) { CreateFiles(); if (copy_icon) { const auto& src_icon = g_mnt->GetHostPath("/app0/sce_sys/save_data.png"); if (fs::exists(src_icon)) { auto output_icon = GetIconPath(); if (fs::exists(output_icon)) { fs::remove(output_icon); } fs::copy_file(src_icon, output_icon); } } exists = true; } else { if (!ignore_corrupt && fs::exists(corrupt_file_path)) { throw std::filesystem::filesystem_error( "Corrupted save data", corrupt_file_path, std::make_error_code(std::errc::illegal_byte_sequence)); } if (!param_sfo.Open(param_sfo_path)) { throw std::filesystem::filesystem_error( "Failed to read param.sfo", param_sfo_path, std::make_error_code(std::errc::illegal_byte_sequence)); } } if (!ignore_corrupt && !read_only) { int err = corrupt_file.Open(corrupt_file_path, Common::FS::FileAccessMode::Write); if (err != 0) { throw std::filesystem::filesystem_error( "Failed to open corrupted file", corrupt_file_path, std::make_error_code(std::errc::illegal_byte_sequence)); } } max_blocks = static_cast<int>(GetMaxBlockFromSFO(param_sfo)); g_mnt->Mount(save_path, mount_point, read_only); mounted = true; this->read_only = read_only; } void SaveInstance::Umount() { if (!mounted) { UNREACHABLE_MSG("Save instance is not mounted"); return; } mounted = false; const bool ok = param_sfo.Encode(param_sfo_path); if (!ok) { throw std::filesystem::filesystem_error("Failed to write param.sfo", param_sfo_path, std::make_error_code(std::errc::permission_denied)); } param_sfo = PSF(); corrupt_file.Close(); fs::remove(corrupt_file_path); g_mnt->Unmount(save_path, mount_point); } void SaveInstance::CreateFiles() { const auto sce_sys_dir = save_path / sce_sys; fs::create_directories(sce_sys_dir); SetupDefaultParamSFO(param_sfo, dir_name, game_serial); param_sfo.AddBinary(std::string{SaveParams::SAVEDATA_BLOCKS}, max_blocks, true); const bool ok = param_sfo.Encode(param_sfo_path); if (!ok) { throw std::filesystem::filesystem_error("Failed to write param.sfo", param_sfo_path, std::make_error_code(std::errc::permission_denied)); } } } // namespace Libraries::SaveData
8,072
C++
.cpp
193
34.367876
100
0.625962
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,560
save_backup.cpp
shadps4-emu_shadPS4/src/core/libraries/save_data/save_backup.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <deque> #include <mutex> #include <semaphore> #include <magic_enum.hpp> #include "save_backup.h" #include "save_instance.h" #include "common/logging/log.h" #include "common/logging/log_entry.h" #include "common/polyfill_thread.h" #include "common/thread.h" constexpr std::string_view sce_sys = "sce_sys"; // system folder inside save constexpr std::string_view backup_dir = "sce_backup"; // backup folder constexpr std::string_view backup_dir_tmp = "sce_backup_tmp"; // in-progress backup folder constexpr std::string_view backup_dir_old = "sce_backup_old"; // previous backup folder namespace fs = std::filesystem; namespace Libraries::SaveData::Backup { static std::jthread g_backup_thread; static std::counting_semaphore g_backup_thread_semaphore{0}; static std::mutex g_backup_running_mutex; static std::mutex g_backup_queue_mutex; static std::deque<BackupRequest> g_backup_queue; static std::deque<BackupRequest> g_result_queue; static std::atomic_int g_backup_progress = 0; static std::atomic g_backup_status = WorkerStatus::NotStarted; static void backup(const std::filesystem::path& dir_name) { std::unique_lock lk{g_backup_running_mutex}; if (!fs::exists(dir_name)) { return; } const auto backup_dir = dir_name / ::backup_dir; const auto backup_dir_tmp = dir_name / ::backup_dir_tmp; const auto backup_dir_old = dir_name / ::backup_dir_old; fs::remove_all(backup_dir_tmp); fs::remove_all(backup_dir_old); std::vector<std::filesystem::path> backup_files; for (const auto& entry : fs::directory_iterator(dir_name)) { const auto filename = entry.path().filename(); if (filename != ::backup_dir) { backup_files.push_back(entry.path()); } } g_backup_progress = 0; int total_count = static_cast<int>(backup_files.size()); int current_count = 0; fs::create_directory(backup_dir_tmp); for (const auto& file : backup_files) { fs::copy(file, backup_dir_tmp / file.filename(), fs::copy_options::recursive); current_count++; g_backup_progress = current_count * 100 / total_count; } bool has_existing_backup = fs::exists(backup_dir); if (has_existing_backup) { fs::rename(backup_dir, backup_dir_old); } fs::rename(backup_dir_tmp, backup_dir); if (has_existing_backup) { fs::remove_all(backup_dir_old); } } static void BackupThreadBody() { Common::SetCurrentThreadName("shadPS4:SaveData_BackupThread"); while (g_backup_status != WorkerStatus::Stopping) { g_backup_status = WorkerStatus::Waiting; bool wait; BackupRequest req; { std::scoped_lock lk{g_backup_queue_mutex}; wait = g_backup_queue.empty(); if (!wait) { req = g_backup_queue.front(); } } if (wait) { g_backup_thread_semaphore.acquire(); { std::scoped_lock lk{g_backup_queue_mutex}; if (g_backup_queue.empty()) { continue; } req = g_backup_queue.front(); } } if (req.save_path.empty()) { break; } g_backup_status = WorkerStatus::Running; LOG_INFO(Lib_SaveData, "Backing up the following directory: {}", fmt::UTF(req.save_path.u8string())); try { backup(req.save_path); } catch (const std::filesystem::filesystem_error& err) { LOG_ERROR(Lib_SaveData, "Failed to backup {}: {}", fmt::UTF(req.save_path.u8string()), err.what()); } LOG_DEBUG(Lib_SaveData, "Backing up the following directory: {} finished", fmt::UTF(req.save_path.u8string())); { std::scoped_lock lk{g_backup_queue_mutex}; g_backup_queue.front().done = true; } std::this_thread::sleep_for(std::chrono::seconds(5)); // Don't backup too often { std::scoped_lock lk{g_backup_queue_mutex}; g_backup_queue.pop_front(); g_result_queue.push_back(std::move(req)); if (g_result_queue.size() > 20) { g_result_queue.pop_front(); } } } g_backup_status = WorkerStatus::NotStarted; } void StartThread() { if (g_backup_status != WorkerStatus::NotStarted) { return; } LOG_DEBUG(Lib_SaveData, "Starting backup thread"); g_backup_status = WorkerStatus::Waiting; g_backup_thread = std::jthread{BackupThreadBody}; } void StopThread() { if (g_backup_status == WorkerStatus::NotStarted || g_backup_status == WorkerStatus::Stopping) { return; } LOG_DEBUG(Lib_SaveData, "Stopping backup thread"); { std::scoped_lock lk{g_backup_queue_mutex}; g_backup_queue.emplace_back(BackupRequest{}); } g_backup_thread_semaphore.release(); g_backup_status = WorkerStatus::Stopping; } bool NewRequest(OrbisUserServiceUserId user_id, std::string_view title_id, std::string_view dir_name, OrbisSaveDataEventType origin) { auto save_path = SaveInstance::MakeDirSavePath(user_id, title_id, dir_name); if (g_backup_status != WorkerStatus::Waiting && g_backup_status != WorkerStatus::Running) { LOG_ERROR(Lib_SaveData, "Called backup while status is {}. Backup request to {} ignored", magic_enum::enum_name(g_backup_status.load()), fmt::UTF(save_path.u8string())); return false; } { std::scoped_lock lk{g_backup_queue_mutex}; for (const auto& it : g_backup_queue) { if (it.dir_name == dir_name) { LOG_TRACE(Lib_SaveData, "Backup request to {} ignored. Already queued", dir_name); return false; } } g_backup_queue.push_back(BackupRequest{ .user_id = user_id, .title_id = std::string{title_id}, .dir_name = std::string{dir_name}, .origin = origin, .save_path = std::move(save_path), }); } g_backup_thread_semaphore.release(); return true; } bool Restore(const std::filesystem::path& save_path) { LOG_INFO(Lib_SaveData, "Restoring backup for {}", fmt::UTF(save_path.u8string())); std::unique_lock lk{g_backup_running_mutex}; if (!fs::exists(save_path) || !fs::exists(save_path / backup_dir)) { return false; } for (const auto& entry : fs::directory_iterator(save_path)) { const auto filename = entry.path().filename(); if (filename != backup_dir) { fs::remove_all(entry.path()); } } for (const auto& entry : fs::directory_iterator(save_path / backup_dir)) { const auto filename = entry.path().filename(); fs::copy(entry.path(), save_path / filename, fs::copy_options::recursive); } return true; } WorkerStatus GetWorkerStatus() { return g_backup_status; } bool IsBackupExecutingFor(const std::filesystem::path& save_path) { std::scoped_lock lk{g_backup_queue_mutex}; const auto& it = std::ranges::find(g_backup_queue, save_path, [](const auto& v) { return v.save_path; }); return it != g_backup_queue.end() && !it->done; } std::filesystem::path MakeBackupPath(const std::filesystem::path& save_path) { return save_path / backup_dir; } std::optional<BackupRequest> PopLastEvent() { std::scoped_lock lk{g_backup_queue_mutex}; if (g_result_queue.empty()) { return std::nullopt; } auto req = std::move(g_result_queue.front()); g_result_queue.pop_front(); return req; } void PushBackupEvent(BackupRequest&& req) { std::scoped_lock lk{g_backup_queue_mutex}; g_result_queue.push_back(std::move(req)); if (g_result_queue.size() > 20) { g_result_queue.pop_front(); } } float GetProgress() { return static_cast<float>(g_backup_progress) / 100.0f; } void ClearProgress() { g_backup_progress = 0; } } // namespace Libraries::SaveData::Backup
8,209
C++
.cpp
214
31.443925
99
0.625126
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,561
save_memory.cpp
shadps4-emu_shadPS4/src/core/libraries/save_data/save_memory.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "save_memory.h" #include <condition_variable> #include <filesystem> #include <mutex> #include <utility> #include <fmt/format.h> #include <core/libraries/system/msgdialog_ui.h> #include "common/assert.h" #include "common/logging/log.h" #include "common/polyfill_thread.h" #include "common/singleton.h" #include "common/thread.h" #include "core/file_sys/fs.h" #include "save_instance.h" using Common::FS::IOFile; namespace fs = std::filesystem; constexpr std::string_view sce_sys = "sce_sys"; // system folder inside save constexpr std::string_view DirnameSaveDataMemory = "sce_sdmemory"; constexpr std::string_view FilenameSaveDataMemory = "memory.dat"; namespace Libraries::SaveData::SaveMemory { static Core::FileSys::MntPoints* g_mnt = Common::Singleton<Core::FileSys::MntPoints>::Instance(); static OrbisUserServiceUserId g_user_id{}; static std::string g_game_serial{}; static std::filesystem::path g_save_path{}; static std::filesystem::path g_param_sfo_path{}; static PSF g_param_sfo; static bool g_save_memory_initialized = false; static std::mutex g_saving_memory_mutex; static std::vector<u8> g_save_memory; static std::filesystem::path g_icon_path; static std::vector<u8> g_icon_memory; static std::condition_variable g_trigger_save_memory; static std::atomic_bool g_saving_memory = false; static std::atomic_bool g_save_event = false; static std::jthread g_save_memory_thread; static std::atomic_bool g_memory_dirty = false; static std::atomic_bool g_param_dirty = false; static std::atomic_bool g_icon_dirty = false; static void SaveFileSafe(void* buf, size_t count, const std::filesystem::path& path) { const auto& dir = path.parent_path(); const auto& name = path.filename(); const auto tmp_path = dir / (name.string() + ".tmp"); IOFile file(tmp_path, Common::FS::FileAccessMode::Write); file.WriteRaw<u8>(buf, count); file.Close(); fs::remove(path); fs::rename(tmp_path, path); } [[noreturn]] void SaveThreadLoop() { Common::SetCurrentThreadName("shadPS4:SaveData_SaveDataMemoryThread"); std::mutex mtx; while (true) { { std::unique_lock lk{mtx}; g_trigger_save_memory.wait(lk); } // Save the memory g_saving_memory = true; std::scoped_lock lk{g_saving_memory_mutex}; try { LOG_DEBUG(Lib_SaveData, "Saving save data memory {}", fmt::UTF(g_save_path.u8string())); if (g_memory_dirty) { g_memory_dirty = false; SaveFileSafe(g_save_memory.data(), g_save_memory.size(), g_save_path / FilenameSaveDataMemory); } if (g_param_dirty) { g_param_dirty = false; static std::vector<u8> buf; g_param_sfo.Encode(buf); SaveFileSafe(buf.data(), buf.size(), g_param_sfo_path); } if (g_icon_dirty) { g_icon_dirty = false; SaveFileSafe(g_icon_memory.data(), g_icon_memory.size(), g_icon_path); } if (g_save_event) { Backup::PushBackupEvent(Backup::BackupRequest{ .user_id = g_user_id, .title_id = g_game_serial, .dir_name = std::string{DirnameSaveDataMemory}, .origin = Backup::OrbisSaveDataEventType::SAVE_DATA_MEMORY_SYNC, .save_path = g_save_path, }); g_save_event = false; } } catch (const fs::filesystem_error& e) { LOG_ERROR(Lib_SaveData, "Failed to save save data memory: {}", e.what()); MsgDialog::ShowMsgDialog(MsgDialog::MsgDialogState{ MsgDialog::MsgDialogState::UserState{ .type = MsgDialog::ButtonType::OK, .msg = fmt::format("Failed to save save data memory.\nCode: <{}>\n{}", e.code().message(), e.what()), }, }); } g_saving_memory = false; } } void SetDirectories(OrbisUserServiceUserId user_id, std::string _game_serial) { g_user_id = user_id; g_game_serial = std::move(_game_serial); g_save_path = SaveInstance::MakeDirSavePath(user_id, g_game_serial, DirnameSaveDataMemory); g_param_sfo_path = SaveInstance::GetParamSFOPath(g_save_path); g_param_sfo = PSF(); g_icon_path = g_save_path / sce_sys / "icon0.png"; } const std::filesystem::path& GetSavePath() { return g_save_path; } size_t CreateSaveMemory(size_t memory_size) { size_t existed_size = 0; static std::once_flag init_save_thread_flag; std::call_once(init_save_thread_flag, [] { g_save_memory_thread = std::jthread{SaveThreadLoop}; }); g_save_memory.resize(memory_size); SaveInstance::SetupDefaultParamSFO(g_param_sfo, std::string{DirnameSaveDataMemory}, g_game_serial); g_save_memory_initialized = true; if (!fs::exists(g_param_sfo_path)) { // Create save memory fs::create_directories(g_save_path / sce_sys); IOFile memory_file{g_save_path / FilenameSaveDataMemory, Common::FS::FileAccessMode::Write}; bool ok = memory_file.SetSize(memory_size); if (!ok) { LOG_ERROR(Lib_SaveData, "Failed to set memory size"); throw std::filesystem::filesystem_error( "Failed to set save memory size", g_save_path / FilenameSaveDataMemory, std::make_error_code(std::errc::no_space_on_device)); } memory_file.Close(); } else { // Load save memory bool ok = g_param_sfo.Open(g_param_sfo_path); if (!ok) { LOG_ERROR(Lib_SaveData, "Failed to open SFO at {}", fmt::UTF(g_param_sfo_path.u8string())); throw std::filesystem::filesystem_error( "failed to open SFO", g_param_sfo_path, std::make_error_code(std::errc::illegal_byte_sequence)); } IOFile memory_file{g_save_path / FilenameSaveDataMemory, Common::FS::FileAccessMode::Read}; if (!memory_file.IsOpen()) { LOG_ERROR(Lib_SaveData, "Failed to open save memory"); throw std::filesystem::filesystem_error( "failed to open save memory", g_save_path / FilenameSaveDataMemory, std::make_error_code(std::errc::permission_denied)); } size_t save_size = memory_file.GetSize(); existed_size = save_size; memory_file.Seek(0); memory_file.ReadRaw<u8>(g_save_memory.data(), std::min(save_size, memory_size)); memory_file.Close(); } return existed_size; } void SetIcon(void* buf, size_t buf_size) { if (buf == nullptr) { const auto& src_icon = g_mnt->GetHostPath("/app0/sce_sys/save_data.png"); if (fs::exists(src_icon)) { if (fs::exists(g_icon_path)) { fs::remove(g_icon_path); } fs::copy_file(src_icon, g_icon_path); } if (fs::exists(g_icon_path)) { IOFile file(g_icon_path, Common::FS::FileAccessMode::Read); size_t size = file.GetSize(); file.Seek(0); g_icon_memory.resize(size); file.ReadRaw<u8>(g_icon_memory.data(), size); file.Close(); } } else { g_icon_memory.resize(buf_size); std::memcpy(g_icon_memory.data(), buf, buf_size); IOFile file(g_icon_path, Common::FS::FileAccessMode::Write); file.Seek(0); file.WriteRaw<u8>(g_icon_memory.data(), buf_size); file.Close(); } } void WriteIcon(void* buf, size_t buf_size) { if (buf_size != g_icon_memory.size()) { g_icon_memory.resize(buf_size); } std::memcpy(g_icon_memory.data(), buf, buf_size); g_icon_dirty = true; } bool IsSaveMemoryInitialized() { return g_save_memory_initialized; } PSF& GetParamSFO() { return g_param_sfo; } std::span<u8> GetIcon() { return {g_icon_memory}; } void SaveSFO(bool sync) { if (!sync) { g_param_dirty = true; return; } const bool ok = g_param_sfo.Encode(g_param_sfo_path); if (!ok) { LOG_ERROR(Lib_SaveData, "Failed to encode param.sfo"); throw std::filesystem::filesystem_error("Failed to write param.sfo", g_param_sfo_path, std::make_error_code(std::errc::permission_denied)); } } bool IsSaving() { return g_saving_memory; } bool TriggerSaveWithoutEvent() { if (g_saving_memory) { return false; } g_trigger_save_memory.notify_one(); return true; } bool TriggerSave() { if (g_saving_memory) { return false; } g_save_event = true; g_trigger_save_memory.notify_one(); return true; } void ReadMemory(void* buf, size_t buf_size, int64_t offset) { std::scoped_lock lk{g_saving_memory_mutex}; if (offset + buf_size > g_save_memory.size()) { UNREACHABLE_MSG("ReadMemory out of bounds"); } std::memcpy(buf, g_save_memory.data() + offset, buf_size); } void WriteMemory(void* buf, size_t buf_size, int64_t offset) { std::scoped_lock lk{g_saving_memory_mutex}; if (offset + buf_size > g_save_memory.size()) { g_save_memory.resize(offset + buf_size); } std::memcpy(g_save_memory.data() + offset, buf, buf_size); g_memory_dirty = true; } } // namespace Libraries::SaveData::SaveMemory
9,658
C++
.cpp
246
31.430894
100
0.613316
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,562
savedatadialog_ui.cpp
shadps4-emu_shadPS4/src/core/libraries/save_data/dialog/savedatadialog_ui.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <fmt/chrono.h> #include <imgui.h> #include <magic_enum.hpp> #include "common/elf_info.h" #include "common/singleton.h" #include "common/string_util.h" #include "core/file_sys/fs.h" #include "core/libraries/save_data/save_instance.h" #include "imgui/imgui_std.h" #include "savedatadialog_ui.h" using namespace ImGui; using namespace Libraries::CommonDialog; using Common::ElfInfo; constexpr u32 OrbisSaveDataBlockSize = 32768; // 32 KiB constexpr auto SAVE_ICON_SIZE = ImVec2{152.0f, 85.0f}; constexpr auto SAVE_ICON_PADDING = ImVec2{8.0f, 2.0f}; static constexpr ImVec2 BUTTON_SIZE{100.0f, 30.0f}; constexpr auto FOOTER_HEIGHT = BUTTON_SIZE.y + 15.0f; static constexpr float PROGRESS_BAR_WIDTH{0.8f}; static ::Core::FileSys::MntPoints* g_mnt = Common::Singleton<::Core::FileSys::MntPoints>::Instance(); static std::string SpaceSizeToString(size_t size) { std::string size_str; if (size > 1024 * 1024 * 1024) { // > 1GB size_str = fmt::format("{:.2f} GB", double(size / 1024 / 1024) / 1024.0f); } else if (size > 1024 * 1024) { // > 1MB size_str = fmt::format("{:.2f} MB", double(size / 1024) / 1024.0f); } else if (size > 1024) { // > 1KB size_str = fmt::format("{:.2f} KB", double(size) / 1024.0f); } else { size_str = fmt::format("{} B", size); } return size_str; } namespace Libraries::SaveData::Dialog { void SaveDialogResult::CopyTo(OrbisSaveDataDialogResult& result) const { result.mode = this->mode; result.result = this->result; result.buttonId = this->button_id; if (mode == SaveDataDialogMode::LIST || ElfInfo::Instance().FirmwareVer() >= ElfInfo::FW_45) { if (result.dirName != nullptr) { result.dirName->data.FromString(this->dir_name); } if (result.param != nullptr && this->param.GetString(SaveParams::MAINTITLE).has_value()) { result.param->FromSFO(this->param); } } result.userData = this->user_data; } SaveDialogState::SaveDialogState(const OrbisSaveDataDialogParam& param) { this->mode = param.mode; this->type = param.dispType; this->user_data = param.userData; if (param.optionParam != nullptr) { this->enable_back = {param.optionParam->back == OptionBack::ENABLE}; } const auto& game_serial = Common::ElfInfo::Instance().GameSerial(); const auto item = param.items; this->user_id = item->userId; if (item->titleId == nullptr) { this->title_id = game_serial; } else { this->title_id = item->titleId->data.to_string(); } if (item->dirName != nullptr) { for (u32 i = 0; i < item->dirNameNum; i++) { const auto dir_name = item->dirName[i].data.to_view(); if (dir_name.empty()) { continue; } auto dir_path = SaveInstance::MakeDirSavePath(user_id, title_id, dir_name); auto param_sfo_path = dir_path / "sce_sys" / "param.sfo"; if (!std::filesystem::exists(param_sfo_path)) { continue; } PSF param_sfo; param_sfo.Open(param_sfo_path); auto last_write = param_sfo.GetLastWrite(); #if defined(_WIN32) && !defined(__GNUC__) && !defined(__MINGW32__) && !defined(__MINGW64__) auto utc_time = std::chrono::file_clock::to_utc(last_write); #else auto utc_time = std::chrono::file_clock::to_sys(last_write); #endif std::string date_str = fmt::format("{:%d %b, %Y %R}", utc_time); size_t size = Common::FS::GetDirectorySize(dir_path); std::string size_str = SpaceSizeToString(size); auto icon_path = dir_path / "sce_sys" / "icon0.png"; RefCountedTexture icon; if (std::filesystem::exists(icon_path)) { icon = RefCountedTexture::DecodePngFile(icon_path); } bool is_corrupted = std::filesystem::exists(dir_path / "sce_sys" / "corrupted"); this->save_list.emplace_back(Item{ .dir_name = std::string{dir_name}, .icon = icon, .title = std::string{param_sfo.GetString(SaveParams::MAINTITLE).value_or("Unknown")}, .subtitle = std::string{param_sfo.GetString(SaveParams::SUBTITLE).value_or("")}, .details = std::string{param_sfo.GetString(SaveParams::DETAIL).value_or("")}, .date = date_str, .size = size_str, .last_write = param_sfo.GetLastWrite(), .pfo = param_sfo, .is_corrupted = is_corrupted, }); } } if (type == DialogType::SAVE && item->newItem != nullptr) { RefCountedTexture icon; std::string title{"New Save"}; const auto new_item = item->newItem; if (new_item->iconBuf && new_item->iconSize) { auto buf = (u8*)new_item->iconBuf; icon = RefCountedTexture::DecodePngTexture({buf, buf + new_item->iconSize}); } else { const auto& src_icon = g_mnt->GetHostPath("/app0/sce_sys/save_data.png"); if (std::filesystem::exists(src_icon)) { icon = RefCountedTexture::DecodePngFile(src_icon); } } if (new_item->title != nullptr) { title = std::string{new_item->title}; } this->new_item = Item{ .dir_name = "", .icon = icon, .title = title, }; } if (item->focusPos != FocusPos::DIRNAME) { this->focus_pos = item->focusPos; } else { this->focus_pos = item->focusPosDirName->data.to_string(); } this->style = item->itemStyle; switch (mode) { case SaveDataDialogMode::USER_MSG: { this->state = UserState{param}; } break; case SaveDataDialogMode::SYSTEM_MSG: this->state = SystemState{*this, param}; break; case SaveDataDialogMode::ERROR_CODE: { this->state = ErrorCodeState{param}; } break; case SaveDataDialogMode::PROGRESS_BAR: { this->state = ProgressBarState{*this, param}; } break; default: break; } } SaveDialogState::UserState::UserState(const OrbisSaveDataDialogParam& param) { auto& user = *param.userMsgParam; this->type = user.buttonType; this->msg_type = user.msgType; this->msg = user.msg != nullptr ? std::string{user.msg} : std::string{}; } SaveDialogState::SystemState::SystemState(const SaveDialogState& state, const OrbisSaveDataDialogParam& param) { #define M(save, load, del) \ if (type == DialogType::SAVE) \ this->msg = save; \ else if (type == DialogType::LOAD) \ this->msg = load; \ else if (type == DialogType::DELETE) \ this->msg = del; \ else \ UNREACHABLE() auto type = param.dispType; auto& sys = *param.sysMsgParam; switch (sys.msgType) { case SystemMessageType::NODATA: { return_cancel = true; this->msg = "There is no saved data"; } break; case SystemMessageType::CONFIRM: show_no = true; M("Do you want to save?", "Do you want to load this saved data?", "Do you want to delete this saved data?"); break; case SystemMessageType::OVERWRITE: show_no = true; M("Do you want to overwrite the existing saved data?", "##UNKNOWN##", "##UNKNOWN##"); break; case SystemMessageType::NOSPACE: return_cancel = true; M(fmt::format( "There is not enough space to save the data. To continue {} free space is required.", SpaceSizeToString(sys.value * OrbisSaveDataBlockSize)), "##UNKNOWN##", "##UNKNOWN##"); break; case SystemMessageType::PROGRESS: hide_ok = true; show_cancel = state.enable_back.value_or(false); M("Saving...", "Loading...", "Deleting..."); break; case SystemMessageType::FILE_CORRUPTED: return_cancel = true; this->msg = "The saved data is corrupted."; break; case SystemMessageType::FINISHED: return_cancel = true; M("Saved successfully.", "Loading complete.", "Deletion complete."); break; case SystemMessageType::NOSPACE_CONTINUABLE: return_cancel = true; M(fmt::format("There is not enough space to save the data. {} free space is required.", SpaceSizeToString(sys.value * OrbisSaveDataBlockSize)), "##UNKNOWN##", "##UNKNOWN##"); break; case SystemMessageType::CORRUPTED_AND_DELETED: { show_cancel = state.enable_back.value_or(true); const char* msg1 = "The saved data is corrupted and will be deleted."; M(msg1, msg1, "##UNKNOWN##"); } break; case SystemMessageType::CORRUPTED_AND_CREATED: { show_cancel = state.enable_back.value_or(true); const char* msg2 = "The saved data is corrupted. This saved data will be deleted and a new " "one will be created."; M(msg2, msg2, "##UNKNOWN##"); } break; case SystemMessageType::CORRUPTED_AND_RESTORE: { show_cancel = state.enable_back.value_or(true); const char* msg3 = "The saved data is corrupted. The data that was backed up by the system will be " "restored."; M(msg3, msg3, "##UNKNOWN##"); } break; case SystemMessageType::TOTAL_SIZE_EXCEEDED: M("Cannot create more saved data", "##UNKNOWN##", "##UNKNOWN##"); break; default: msg = fmt::format("Unknown message type: {}", magic_enum::enum_name(sys.msgType)); break; } #undef M } SaveDialogState::ErrorCodeState::ErrorCodeState(const OrbisSaveDataDialogParam& param) { auto& err = *param.errorCodeParam; constexpr auto NOT_FOUND = 0x809F0008; constexpr auto BROKEN = 0x809F000F; switch (err.errorCode) { case NOT_FOUND: this->error_msg = "There is not saved data."; break; case BROKEN: this->error_msg = "The data is corrupted."; break; default: this->error_msg = fmt::format("An error has occurred. ({:X})", err.errorCode); break; } } SaveDialogState::ProgressBarState::ProgressBarState(const SaveDialogState& state, const OrbisSaveDataDialogParam& param) { static auto fw_ver = ElfInfo::Instance().FirmwareVer(); this->progress = 0; auto& bar = *param.progressBarParam; if (bar.msg != nullptr) { this->msg = std::string{bar.msg}; } else { switch (bar.sysMsgType) { case ProgressSystemMessageType::INVALID: this->msg = ""; break; case ProgressSystemMessageType::PROGRESS: switch (state.type) { case DialogType::SAVE: this->msg = "Saving..."; break; case DialogType::LOAD: this->msg = "Loading..."; break; case DialogType::DELETE: this->msg = "Deleting..."; break; } break; case ProgressSystemMessageType::RESTORE: this->msg = "Restoring saved data..."; break; } } } SaveDialogUi::SaveDialogUi(SaveDialogState* state, Status* status, SaveDialogResult* result) : state(state), status(status), result(result) { if (status && *status == Status::RUNNING) { first_render = true; AddLayer(this); } } SaveDialogUi::~SaveDialogUi() { Finish(ButtonId::INVALID); } SaveDialogUi::SaveDialogUi(SaveDialogUi&& other) noexcept : Layer(other), state(other.state), status(other.status), result(other.result) { std::scoped_lock lock(draw_mutex, other.draw_mutex); other.state = nullptr; other.status = nullptr; other.result = nullptr; if (status && *status == Status::RUNNING) { first_render = true; AddLayer(this); } } SaveDialogUi& SaveDialogUi::operator=(SaveDialogUi other) { std::scoped_lock lock(draw_mutex, other.draw_mutex); using std::swap; swap(state, other.state); swap(status, other.status); swap(result, other.result); if (status && *status == Status::RUNNING) { first_render = true; AddLayer(this); } return *this; } void SaveDialogUi::Finish(ButtonId buttonId, Result r) { std::unique_lock lock(draw_mutex); if (result) { result->mode = this->state->mode; result->result = r; result->button_id = buttonId; result->user_data = this->state->user_data; if (state && state->mode != SaveDataDialogMode::LIST && !state->save_list.empty()) { result->dir_name = state->save_list.front().dir_name; } } if (status) { *status = Status::FINISHED; } RemoveLayer(this); } void SaveDialogUi::Draw() { std::unique_lock lock{draw_mutex}; if (status == nullptr || *status != Status::RUNNING || state == nullptr) { return; } const auto& ctx = *GetCurrentContext(); const auto& io = ctx.IO; ImVec2 window_size; if (state->GetMode() == SaveDataDialogMode::LIST) { window_size = ImVec2{ std::min(io.DisplaySize.x - 200.0f, 1100.0f), std::min(io.DisplaySize.y - 100.0f, 700.0f), }; } else { window_size = ImVec2{ std::min(io.DisplaySize.x, 600.0f), std::min(io.DisplaySize.y, 300.0f), }; } CentralizeNextWindow(); SetNextWindowSize(window_size); SetNextWindowCollapsed(false); if (first_render || !io.NavActive) { SetNextWindowFocus(); } if (Begin("Save Data Dialog##SaveDataDialog", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoSavedSettings)) { DrawPrettyBackground(); Separator(); // Draw title bigger SetWindowFontScale(1.7f); switch (state->type) { case DialogType::SAVE: TextUnformatted("Save"); break; case DialogType::LOAD: TextUnformatted("Load"); break; case DialogType::DELETE: TextUnformatted("Delete"); break; } SetWindowFontScale(1.0f); Separator(); BeginGroup(); switch (state->GetMode()) { case SaveDataDialogMode::LIST: DrawList(); break; case SaveDataDialogMode::USER_MSG: DrawUser(); break; case SaveDataDialogMode::SYSTEM_MSG: DrawSystemMessage(); break; case SaveDataDialogMode::ERROR_CODE: DrawErrorCode(); break; case SaveDataDialogMode::PROGRESS_BAR: DrawProgressBar(); break; default: TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "!!!Unknown dialog mode!!!"); } EndGroup(); } End(); first_render = false; if (*status == Status::FINISHED) { if (state) { *state = SaveDialogState{}; } state = nullptr; status = nullptr; result = nullptr; } } void SaveDialogUi::DrawItem(int _id, const SaveDialogState::Item& item, bool clickable) { constexpr auto text_spacing = 0.95f; auto& ctx = *GetCurrentContext(); auto& window = *ctx.CurrentWindow; auto content_region_avail = GetContentRegionAvail(); const auto outer_pos = window.DC.CursorPos; const auto pos = outer_pos + SAVE_ICON_PADDING; const ImVec2 size = {content_region_avail.x - SAVE_ICON_PADDING.x, SAVE_ICON_SIZE.y + SAVE_ICON_PADDING.y}; const ImRect bb{outer_pos, outer_pos + size + SAVE_ICON_PADDING}; const ImGuiID id = GetID(_id); ItemSize(size + ImVec2{0.0f, SAVE_ICON_PADDING.y * 2.0f}); if (!ItemAdd(bb, id)) { return; } window.DrawList->AddRectFilled(bb.Min + SAVE_ICON_PADDING, bb.Max - SAVE_ICON_PADDING, GetColorU32(ImVec4{0.3f})); bool hovered = false; if (clickable) { bool held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); if (pressed) { result->dir_name = item.dir_name; result->param = item.pfo; Finish(ButtonId::INVALID); } RenderNavHighlight(bb, id); } if (item.icon) { auto texture = item.icon.GetTexture(); window.DrawList->AddImage(texture.im_id, pos, pos + SAVE_ICON_SIZE); } else { // placeholder window.DrawList->AddRectFilled(pos, pos + SAVE_ICON_SIZE, GetColorU32(ImVec4{0.7f})); } auto pos_x = SAVE_ICON_SIZE.x + 5.0f; auto pos_y = 2.0f; if (!item.title.empty()) { const char* begin = &item.title.front(); const char* end = &item.title.back() + 1; SetWindowFontScale(1.5f); RenderText(pos + ImVec2{pos_x, pos_y}, begin, end, false); pos_y += ctx.FontSize * text_spacing; } SetWindowFontScale(1.1f); if (item.is_corrupted) { pos_y -= ctx.FontSize * text_spacing * 0.3f; const auto bright = (int)std::abs(std::sin(ctx.Time) * 0.15f * 255.0f); PushStyleColor(ImGuiCol_Text, IM_COL32(bright + 216, bright, bright, 0xFF)); RenderText(pos + ImVec2{pos_x, pos_y}, "Corrupted", nullptr, false); PopStyleColor(); pos_y += ctx.FontSize * text_spacing * 0.8f; } if (state->style == ItemStyle::TITLE_SUBTITLE_DATESIZE) { if (!item.subtitle.empty()) { const char* begin = &item.subtitle.front(); const char* end = &item.subtitle.back() + 1; RenderText(pos + ImVec2{pos_x, pos_y}, begin, end, false); } pos_y += ctx.FontSize * text_spacing; } { float width = 0.0f; if (!item.date.empty()) { const char* d_begin = &item.date.front(); const char* d_end = &item.date.back() + 1; width = CalcTextSize(d_begin, d_end).x + 15.0f; RenderText(pos + ImVec2{pos_x, pos_y}, d_begin, d_end, false); } if (!item.size.empty()) { const char* s_begin = &item.size.front(); const char* s_end = &item.size.back() + 1; RenderText(pos + ImVec2{pos_x + width, pos_y}, s_begin, s_end, false); } pos_y += ctx.FontSize * text_spacing; } if (state->style == ItemStyle::TITLE_DATASIZE_SUBTITLE && !item.subtitle.empty()) { const char* begin = &item.subtitle.front(); const char* end = &item.subtitle.back() + 1; RenderText(pos + ImVec2{pos_x, pos_y}, begin, end, false); } SetWindowFontScale(1.0f); if (hovered) { window.DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border), 0.0f, 0, 2.0f); } } void SaveDialogUi::DrawList() { auto availableSize = GetContentRegionAvail(); constexpr auto footerHeight = 30.0f; availableSize.y -= footerHeight + 1.0f; BeginChild("##ScrollingRegion", availableSize, ImGuiChildFlags_NavFlattened); int i = 0; if (state->new_item.has_value()) { DrawItem(i++, state->new_item.value()); } for (const auto& item : state->save_list) { DrawItem(i++, item); } if (first_render) { // Make the initial focus if (std::holds_alternative<FocusPos>(state->focus_pos)) { auto pos = std::get<FocusPos>(state->focus_pos); if (pos == FocusPos::LISTHEAD || pos == FocusPos::DATAHEAD) { SetItemCurrentNavFocus(GetID(0)); } else if (pos == FocusPos::LISTTAIL || pos == FocusPos::DATATAIL) { SetItemCurrentNavFocus(GetID(std::max(i - 1, 0))); } else { // Date int idx = 0; int max_idx = 0; bool is_min = pos == FocusPos::DATAOLDEST; std::filesystem::file_time_type max_write{}; if (state->new_item.has_value()) { idx++; } for (const auto& item : state->save_list) { if (item.last_write > max_write ^ is_min) { max_write = item.last_write; max_idx = idx; } idx++; } SetItemCurrentNavFocus(GetID(max_idx)); } } else if (std::holds_alternative<std::string>(state->focus_pos)) { auto dir_name = std::get<std::string>(state->focus_pos); if (dir_name.empty()) { SetItemCurrentNavFocus(GetID(0)); } else { int idx = 0; if (state->new_item.has_value()) { if (dir_name == state->new_item->dir_name) { SetItemCurrentNavFocus(GetID(idx)); } idx++; } for (const auto& item : state->save_list) { if (item.dir_name == dir_name) { SetItemCurrentNavFocus(GetID(idx)); break; } idx++; } } } } EndChild(); Separator(); if (state->enable_back.value_or(true)) { constexpr auto back = "Back"; constexpr float pad = 7.0f; const auto txt_size = CalcTextSize(back); const auto button_size = ImVec2{ std::max(txt_size.x, 100.0f) + pad * 2.0f, footerHeight - pad, }; SetCursorPosX(GetContentRegionAvail().x - button_size.x); if (Button(back, button_size)) { result->dir_name.clear(); Finish(ButtonId::INVALID, Result::USER_CANCELED); } if (IsKeyPressed(ImGuiKey_GamepadFaceRight)) { SetItemCurrentNavFocus(); } } } void SaveDialogUi::DrawUser() { const auto& user_state = state->GetState<SaveDialogState::UserState>(); const auto btn_type = user_state.type; const auto ws = GetWindowSize(); if (!state->save_list.empty()) { DrawItem(0, state->save_list.front(), false); } else if (state->new_item) { DrawItem(0, *state->new_item, false); } auto has_btn = btn_type != ButtonType::NONE; ImVec2 btn_space; if (has_btn) { btn_space = ImVec2{0.0f, FOOTER_HEIGHT}; } const auto& msg = user_state.msg; if (!msg.empty()) { const char* begin = &msg.front(); const char* end = &msg.back() + 1; if (user_state.msg_type == UserMessageType::ERROR) { PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); // Maybe make the text bold? } DrawCenteredText(begin, end, GetContentRegionAvail() - btn_space); if (user_state.msg_type == UserMessageType::ERROR) { PopStyleColor(); } } if (has_btn) { int count = 1; if (btn_type == ButtonType::YESNO || btn_type == ButtonType::OKCANCEL) { ++count; } SetCursorPos({ ws.x / 2.0f - BUTTON_SIZE.x / 2.0f * static_cast<float>(count), ws.y - FOOTER_HEIGHT + 5.0f, }); BeginGroup(); if (btn_type == ButtonType::YESNO) { if (Button("Yes", BUTTON_SIZE)) { Finish(ButtonId::YES); } SameLine(); if (Button("No", BUTTON_SIZE)) { if (ElfInfo::Instance().FirmwareVer() < ElfInfo::FW_45) { Finish(ButtonId::INVALID, Result::USER_CANCELED); } else { Finish(ButtonId::NO); } } if (first_render || IsKeyPressed(ImGuiKey_GamepadFaceRight)) { SetItemCurrentNavFocus(); } } else { if (Button("OK", BUTTON_SIZE)) { if (btn_type == ButtonType::OK && ElfInfo::Instance().FirmwareVer() < ElfInfo::FW_45) { Finish(ButtonId::INVALID, Result::USER_CANCELED); } else { Finish(ButtonId::OK); } } if (first_render) { SetItemCurrentNavFocus(); } if (btn_type == ButtonType::OKCANCEL) { SameLine(); if (Button("Cancel", BUTTON_SIZE)) { Finish(ButtonId::INVALID, Result::USER_CANCELED); } if (IsKeyPressed(ImGuiKey_GamepadFaceRight)) { SetItemCurrentNavFocus(); } } } EndGroup(); } } void SaveDialogUi::DrawSystemMessage() { const auto& sys_state = state->GetState<SaveDialogState::SystemState>(); if (!state->save_list.empty()) { DrawItem(0, state->save_list.front(), false); } else if (state->new_item) { DrawItem(0, *state->new_item, false); } const auto ws = GetWindowSize(); const auto& msg = sys_state.msg; if (!msg.empty()) { const char* begin = &msg.front(); const char* end = &msg.back() + 1; DrawCenteredText(begin, end, GetContentRegionAvail() - ImVec2{0.0f, FOOTER_HEIGHT}); } int count = 1; if (sys_state.hide_ok) { --count; } if (sys_state.show_no || sys_state.show_cancel) { ++count; } SetCursorPos({ ws.x / 2.0f - BUTTON_SIZE.x / 2.0f * static_cast<float>(count), ws.y - FOOTER_HEIGHT + 5.0f, }); BeginGroup(); if (Button(sys_state.show_no ? "Yes" : "OK", BUTTON_SIZE)) { if (sys_state.return_cancel && ElfInfo::Instance().FirmwareVer() < ElfInfo::FW_45) { Finish(ButtonId::INVALID, Result::USER_CANCELED); } else { Finish(ButtonId::YES); } } SameLine(); if (sys_state.show_no) { if (Button("No", BUTTON_SIZE)) { if (ElfInfo::Instance().FirmwareVer() < ElfInfo::FW_45) { Finish(ButtonId::INVALID, Result::USER_CANCELED); } else { Finish(ButtonId::NO); } } } else if (sys_state.show_cancel) { if (Button("Cancel", BUTTON_SIZE)) { Finish(ButtonId::INVALID, Result::USER_CANCELED); } } if (first_render || IsKeyPressed(ImGuiKey_GamepadFaceRight)) { SetItemCurrentNavFocus(); } EndGroup(); } void SaveDialogUi::DrawErrorCode() { const auto& err_state = state->GetState<SaveDialogState::ErrorCodeState>(); if (!state->save_list.empty()) { DrawItem(0, state->save_list.front(), false); } else if (state->new_item) { DrawItem(0, *state->new_item, false); } const auto ws = GetWindowSize(); const auto& msg = err_state.error_msg; if (!msg.empty()) { const char* begin = &msg.front(); const char* end = &msg.back() + 1; DrawCenteredText(begin, end, GetContentRegionAvail() - ImVec2{0.0f, FOOTER_HEIGHT}); } SetCursorPos({ ws.x / 2.0f - BUTTON_SIZE.x / 2.0f, ws.y - FOOTER_HEIGHT + 5.0f, }); if (Button("OK", BUTTON_SIZE)) { if (ElfInfo::Instance().FirmwareVer() < ElfInfo::FW_45) { Finish(ButtonId::INVALID, Result::USER_CANCELED); } else { Finish(ButtonId::OK); } } if (first_render) { SetItemCurrentNavFocus(); } } void SaveDialogUi::DrawProgressBar() { const auto& bar_state = state->GetState<SaveDialogState::ProgressBarState>(); const auto ws = GetWindowSize(); if (!state->save_list.empty()) { DrawItem(0, state->save_list.front(), false); } else if (state->new_item) { DrawItem(0, *state->new_item, false); } const auto& msg = bar_state.msg; if (!msg.empty()) { const char* begin = &msg.front(); const char* end = &msg.back() + 1; DrawCenteredText(begin, end, GetContentRegionAvail() - ImVec2{0.0f, FOOTER_HEIGHT}); } SetCursorPos({ ws.x * ((1 - PROGRESS_BAR_WIDTH) / 2.0f), ws.y - FOOTER_HEIGHT + 5.0f, }); ProgressBar(static_cast<float>(bar_state.progress) / 100.0f, {PROGRESS_BAR_WIDTH * ws.x, BUTTON_SIZE.y}); } }; // namespace Libraries::SaveData::Dialog
29,071
C++
.cpp
757
29.443857
100
0.558115
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,563
savedatadialog.cpp
shadps4-emu_shadPS4/src/core/libraries/save_data/dialog/savedatadialog.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/elf_info.h" #include "common/logging/log.h" #include "core/libraries/libs.h" #include "core/libraries/system/commondialog.h" #include "magic_enum.hpp" #include "savedatadialog.h" #include "savedatadialog_ui.h" namespace Libraries::SaveData::Dialog { using CommonDialog::Error; using CommonDialog::Result; using CommonDialog::Status; static auto g_status = Status::NONE; static SaveDialogState g_state{}; static SaveDialogResult g_result{}; static SaveDialogUi g_save_dialog_ui; Error PS4_SYSV_ABI sceSaveDataDialogClose() { LOG_DEBUG(Lib_SaveDataDialog, "called"); if (g_status != Status::RUNNING) { return Error::NOT_RUNNING; } g_save_dialog_ui.Finish(ButtonId::INVALID); g_save_dialog_ui = SaveDialogUi{}; return Error::OK; } Error PS4_SYSV_ABI sceSaveDataDialogGetResult(OrbisSaveDataDialogResult* result) { LOG_DEBUG(Lib_SaveDataDialog, "called"); if (g_status != Status::FINISHED) { return Error::NOT_FINISHED; } if (result == nullptr) { return Error::ARG_NULL; } g_result.CopyTo(*result); return Error::OK; } Status PS4_SYSV_ABI sceSaveDataDialogGetStatus() { LOG_TRACE(Lib_SaveDataDialog, "called status={}", magic_enum::enum_name(g_status)); return g_status; } Error PS4_SYSV_ABI sceSaveDataDialogInitialize() { LOG_DEBUG(Lib_SaveDataDialog, "called"); if (!CommonDialog::g_isInitialized) { return Error::NOT_SYSTEM_INITIALIZED; } if (g_status != Status::NONE) { return Error::ALREADY_INITIALIZED; } if (CommonDialog::g_isUsed) { return Error::BUSY; } g_status = Status::INITIALIZED; CommonDialog::g_isUsed = true; return Error::OK; } s32 PS4_SYSV_ABI sceSaveDataDialogIsReadyToDisplay() { return 1; } Error PS4_SYSV_ABI sceSaveDataDialogOpen(const OrbisSaveDataDialogParam* param) { if (g_status != Status::INITIALIZED && g_status != Status::FINISHED) { LOG_INFO(Lib_SaveDataDialog, "called without initialize"); return Error::INVALID_STATE; } if (param == nullptr) { LOG_DEBUG(Lib_SaveDataDialog, "called param:(NULL)"); return Error::ARG_NULL; } LOG_DEBUG(Lib_SaveDataDialog, "called param->mode: {}", magic_enum::enum_name(param->mode)); ASSERT(param->size == sizeof(OrbisSaveDataDialogParam)); ASSERT(param->baseParam.size == sizeof(CommonDialog::BaseParam)); g_result = {}; g_state = SaveDialogState{*param}; g_status = Status::RUNNING; g_save_dialog_ui = SaveDialogUi(&g_state, &g_status, &g_result); return Error::OK; } Error PS4_SYSV_ABI sceSaveDataDialogProgressBarInc(OrbisSaveDataDialogProgressBarTarget target, u32 delta) { LOG_DEBUG(Lib_SaveDataDialog, "called"); if (g_status != Status::RUNNING) { return Error::NOT_RUNNING; } if (g_state.GetMode() != SaveDataDialogMode::PROGRESS_BAR) { return Error::NOT_SUPPORTED; } if (target != OrbisSaveDataDialogProgressBarTarget::DEFAULT) { return Error::PARAM_INVALID; } g_state.GetState<SaveDialogState::ProgressBarState>().progress += delta; return Error::OK; } Error PS4_SYSV_ABI sceSaveDataDialogProgressBarSetValue(OrbisSaveDataDialogProgressBarTarget target, u32 rate) { LOG_DEBUG(Lib_SaveDataDialog, "called"); if (g_status != Status::RUNNING) { return Error::NOT_RUNNING; } if (g_state.GetMode() != SaveDataDialogMode::PROGRESS_BAR) { return Error::NOT_SUPPORTED; } if (target != OrbisSaveDataDialogProgressBarTarget::DEFAULT) { return Error::PARAM_INVALID; } g_state.GetState<SaveDialogState::ProgressBarState>().progress = rate; return Error::OK; } Error PS4_SYSV_ABI sceSaveDataDialogTerminate() { LOG_DEBUG(Lib_SaveDataDialog, "called"); if (g_status == Status::RUNNING) { sceSaveDataDialogClose(); } if (g_status == Status::NONE) { return Error::NOT_INITIALIZED; } g_save_dialog_ui = SaveDialogUi{}; g_status = Status::NONE; CommonDialog::g_isUsed = false; return Error::OK; } Status PS4_SYSV_ABI sceSaveDataDialogUpdateStatus() { LOG_TRACE(Lib_SaveDataDialog, "called status={}", magic_enum::enum_name(g_status)); return g_status; } void RegisterlibSceSaveDataDialog(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("fH46Lag88XY", "libSceSaveDataDialog", 1, "libSceSaveDataDialog", 1, 1, sceSaveDataDialogClose); LIB_FUNCTION("yEiJ-qqr6Cg", "libSceSaveDataDialog", 1, "libSceSaveDataDialog", 1, 1, sceSaveDataDialogGetResult); LIB_FUNCTION("ERKzksauAJA", "libSceSaveDataDialog", 1, "libSceSaveDataDialog", 1, 1, sceSaveDataDialogGetStatus); LIB_FUNCTION("s9e3+YpRnzw", "libSceSaveDataDialog", 1, "libSceSaveDataDialog", 1, 1, sceSaveDataDialogInitialize); LIB_FUNCTION("en7gNVnh878", "libSceSaveDataDialog", 1, "libSceSaveDataDialog", 1, 1, sceSaveDataDialogIsReadyToDisplay); LIB_FUNCTION("4tPhsP6FpDI", "libSceSaveDataDialog", 1, "libSceSaveDataDialog", 1, 1, sceSaveDataDialogOpen); LIB_FUNCTION("V-uEeFKARJU", "libSceSaveDataDialog", 1, "libSceSaveDataDialog", 1, 1, sceSaveDataDialogProgressBarInc); LIB_FUNCTION("hay1CfTmLyA", "libSceSaveDataDialog", 1, "libSceSaveDataDialog", 1, 1, sceSaveDataDialogProgressBarSetValue); LIB_FUNCTION("YuH2FA7azqQ", "libSceSaveDataDialog", 1, "libSceSaveDataDialog", 1, 1, sceSaveDataDialogTerminate); LIB_FUNCTION("KK3Bdg1RWK0", "libSceSaveDataDialog", 1, "libSceSaveDataDialog", 1, 1, sceSaveDataDialogUpdateStatus); }; } // namespace Libraries::SaveData::Dialog
5,962
C++
.cpp
147
34.482993
100
0.688341
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,564
pad.cpp
shadps4-emu_shadPS4/src/core/libraries/pad/pad.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/assert.h" #include "common/config.h" #include "common/logging/log.h" #include "common/singleton.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" #include "input/controller.h" #include "pad.h" namespace Libraries::Pad { int PS4_SYSV_ABI scePadClose(s32 handle) { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadConnectPort() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadDeviceClassGetExtendedInformation( s32 handle, OrbisPadDeviceClassExtendedInformation* pExtInfo) { LOG_ERROR(Lib_Pad, "(STUBBED) called"); if (Config::getUseSpecialPad()) { pExtInfo->deviceClass = (OrbisPadDeviceClass)Config::getSpecialPadClass(); } return ORBIS_OK; } int PS4_SYSV_ABI scePadDeviceClassParseData(s32 handle, const OrbisPadData* pData, OrbisPadDeviceClassData* pDeviceClassData) { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadDeviceOpen() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadDisableVibration() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadDisconnectDevice() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadDisconnectPort() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadEnableAutoDetect() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadEnableExtensionPort() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadEnableSpecificDeviceClass() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadEnableUsbConnection() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetBluetoothAddress() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetCapability() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetControllerInformation(s32 handle, OrbisPadControllerInformation* pInfo) { LOG_DEBUG(Lib_Pad, "called handle = {}", handle); if (handle < 0) { pInfo->touchPadInfo.pixelDensity = 1; pInfo->touchPadInfo.resolution.x = 1920; pInfo->touchPadInfo.resolution.y = 950; pInfo->stickInfo.deadZoneLeft = 2; pInfo->stickInfo.deadZoneRight = 2; pInfo->connectionType = ORBIS_PAD_PORT_TYPE_STANDARD; pInfo->connectedCount = 1; pInfo->connected = false; pInfo->deviceClass = ORBIS_PAD_DEVICE_CLASS_STANDARD; return SCE_OK; } pInfo->touchPadInfo.pixelDensity = 1; pInfo->touchPadInfo.resolution.x = 1920; pInfo->touchPadInfo.resolution.y = 950; pInfo->stickInfo.deadZoneLeft = 2; pInfo->stickInfo.deadZoneRight = 2; pInfo->connectionType = ORBIS_PAD_PORT_TYPE_STANDARD; pInfo->connectedCount = 1; pInfo->connected = true; pInfo->deviceClass = ORBIS_PAD_DEVICE_CLASS_STANDARD; if (Config::getUseSpecialPad()) { pInfo->connectionType = ORBIS_PAD_PORT_TYPE_SPECIAL; pInfo->deviceClass = (OrbisPadDeviceClass)Config::getSpecialPadClass(); } return SCE_OK; } int PS4_SYSV_ABI scePadGetDataInternal() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetDeviceId() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetDeviceInfo() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetExtControllerInformation(s32 handle, OrbisPadExtendedControllerInformation* pInfo) { LOG_INFO(Lib_Pad, "called handle = {}", handle); pInfo->padType1 = 0; pInfo->padType2 = 0; pInfo->capability = 0; auto res = scePadGetControllerInformation(handle, &pInfo->base); return res; } int PS4_SYSV_ABI scePadGetExtensionUnitInfo() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetFeatureReport() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetHandle(s32 userId, s32 type, s32 index) { LOG_DEBUG(Lib_Pad, "(DUMMY) called"); return 1; } int PS4_SYSV_ABI scePadGetIdleCount() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetInfo() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetInfoByPortType() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetLicenseControllerInformation() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetMotionSensorPosition() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetMotionTimerUnit() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetSphereRadius() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadGetVersionInfo() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadInit() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadIsBlasterConnected() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadIsDS4Connected() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadIsLightBarBaseBrightnessControllable() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadIsMoveConnected() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadIsMoveReproductionModel() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadIsValidHandle() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadMbusInit() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadMbusTerm() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadOpen(s32 userId, s32 type, s32 index, const OrbisPadOpenParam* pParam) { LOG_INFO(Lib_Pad, "(DUMMY) called user_id = {} type = {} index = {}", userId, type, index); if (Config::getUseSpecialPad()) { if (type != ORBIS_PAD_PORT_TYPE_SPECIAL) return ORBIS_PAD_ERROR_DEVICE_NOT_CONNECTED; } else { if (type != ORBIS_PAD_PORT_TYPE_STANDARD && type != ORBIS_PAD_PORT_TYPE_REMOTE_CONTROL) return ORBIS_PAD_ERROR_DEVICE_NOT_CONNECTED; } return 1; // dummy } int PS4_SYSV_ABI scePadOpenExt(s32 userId, s32 type, s32 index, const OrbisPadOpenExtParam* pParam) { LOG_ERROR(Lib_Pad, "(STUBBED) called"); if (Config::getUseSpecialPad()) { if (type != ORBIS_PAD_PORT_TYPE_SPECIAL) return ORBIS_PAD_ERROR_DEVICE_NOT_CONNECTED; } else { if (type != ORBIS_PAD_PORT_TYPE_STANDARD && type != ORBIS_PAD_PORT_TYPE_REMOTE_CONTROL) return ORBIS_PAD_ERROR_DEVICE_NOT_CONNECTED; } return 1; // dummy } int PS4_SYSV_ABI scePadOpenExt2() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadOutputReport() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadRead(s32 handle, OrbisPadData* pData, s32 num) { int connected_count = 0; bool connected = false; Input::State states[64]; auto* controller = Common::Singleton<Input::GameController>::Instance(); int ret_num = controller->ReadStates(states, num, &connected, &connected_count); if (!connected) { ret_num = 1; } for (int i = 0; i < ret_num; i++) { pData[i].buttons = states[i].buttonsState; pData[i].leftStick.x = states[i].axes[static_cast<int>(Input::Axis::LeftX)]; pData[i].leftStick.y = states[i].axes[static_cast<int>(Input::Axis::LeftY)]; pData[i].rightStick.x = states[i].axes[static_cast<int>(Input::Axis::RightX)]; pData[i].rightStick.y = states[i].axes[static_cast<int>(Input::Axis::RightY)]; pData[i].analogButtons.l2 = states[i].axes[static_cast<int>(Input::Axis::TriggerLeft)]; pData[i].analogButtons.r2 = states[i].axes[static_cast<int>(Input::Axis::TriggerRight)]; pData[i].orientation.x = 0.0f; pData[i].orientation.y = 0.0f; pData[i].orientation.z = 0.0f; pData[i].orientation.w = 1.0f; pData[i].acceleration.x = 0.0f; pData[i].acceleration.y = 0.0f; pData[i].acceleration.z = 0.0f; pData[i].angularVelocity.x = 0.0f; pData[i].angularVelocity.y = 0.0f; pData[i].angularVelocity.z = 0.0f; pData[i].touchData.touchNum = (states[i].touchpad[0].state ? 1 : 0) + (states[i].touchpad[1].state ? 1 : 0); pData[i].touchData.touch[0].x = states[i].touchpad[0].x; pData[i].touchData.touch[0].y = states[i].touchpad[0].y; pData[i].touchData.touch[0].id = 1; pData[i].touchData.touch[1].x = states[i].touchpad[1].x; pData[i].touchData.touch[1].y = states[i].touchpad[1].y; pData[i].touchData.touch[1].id = 2; pData[i].connected = connected; pData[i].timestamp = states[i].time; pData[i].connectedCount = connected_count; pData[i].deviceUniqueDataLen = 0; } return ret_num; } int PS4_SYSV_ABI scePadReadBlasterForTracker() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadReadExt() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadReadForTracker() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadReadHistory() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadReadState(s32 handle, OrbisPadData* pData) { auto* controller = Common::Singleton<Input::GameController>::Instance(); int connectedCount = 0; bool isConnected = false; Input::State state; controller->ReadState(&state, &isConnected, &connectedCount); pData->buttons = state.buttonsState; pData->leftStick.x = state.axes[static_cast<int>(Input::Axis::LeftX)]; pData->leftStick.y = state.axes[static_cast<int>(Input::Axis::LeftY)]; pData->rightStick.x = state.axes[static_cast<int>(Input::Axis::RightX)]; pData->rightStick.y = state.axes[static_cast<int>(Input::Axis::RightY)]; pData->analogButtons.l2 = state.axes[static_cast<int>(Input::Axis::TriggerLeft)]; pData->analogButtons.r2 = state.axes[static_cast<int>(Input::Axis::TriggerRight)]; pData->orientation.x = 0; pData->orientation.y = 0; pData->orientation.z = 0; pData->orientation.w = 1; pData->acceleration.x = 0.0f; pData->acceleration.y = 0.0f; pData->acceleration.z = 0.0f; pData->angularVelocity.x = 0.0f; pData->angularVelocity.y = 0.0f; pData->angularVelocity.z = 0.0f; pData->touchData.touchNum = (state.touchpad[0].state ? 1 : 0) + (state.touchpad[1].state ? 1 : 0); pData->touchData.touch[0].x = state.touchpad[0].x; pData->touchData.touch[0].y = state.touchpad[0].y; pData->touchData.touch[0].id = 1; pData->touchData.touch[1].x = state.touchpad[1].x; pData->touchData.touch[1].y = state.touchpad[1].y; pData->touchData.touch[1].id = 2; pData->timestamp = state.time; pData->connected = true; // isConnected; //TODO fix me proper pData->connectedCount = 1; // connectedCount; pData->deviceUniqueDataLen = 0; return SCE_OK; } int PS4_SYSV_ABI scePadReadStateExt() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadResetLightBar(s32 handle) { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadResetLightBarAll() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadResetLightBarAllByPortType() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadResetOrientation(s32 handle) { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadResetOrientationForTracker() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetAngularVelocityDeadbandState(s32 handle, bool bEnable) { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetAutoPowerOffCount() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetButtonRemappingInfo() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetConnection() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetExtensionReport() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetFeatureReport() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetForceIntercepted() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetLightBar(s32 handle, const OrbisPadLightBarParam* pParam) { if (pParam != nullptr) { LOG_INFO(Lib_Pad, "scePadSetLightBar called handle = {} rgb = {} {} {}", handle, pParam->r, pParam->g, pParam->b); if (pParam->r < 0xD && pParam->g < 0xD && pParam->b < 0xD) { LOG_INFO(Lib_Pad, "Invalid lightbar setting"); return ORBIS_PAD_ERROR_INVALID_LIGHTBAR_SETTING; } auto* controller = Common::Singleton<Input::GameController>::Instance(); controller->SetLightBarRGB(pParam->r, pParam->g, pParam->b); return ORBIS_OK; } return ORBIS_PAD_ERROR_INVALID_ARG; } int PS4_SYSV_ABI scePadSetLightBarBaseBrightness() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetLightBarBlinking() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetLightBarForTracker() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetLoginUserNumber() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetMotionSensorState(s32 handle, bool bEnable) { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetProcessFocus() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetProcessPrivilege() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetProcessPrivilegeOfButtonRemapping() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetShareButtonMaskForRemotePlay() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetTiltCorrectionState(s32 handle, bool bEnable) { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetUserColor() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetVibration(s32 handle, const OrbisPadVibrationParam* pParam) { if (pParam != nullptr) { LOG_DEBUG(Lib_Pad, "scePadSetVibration called handle = {} data = {} , {}", handle, pParam->smallMotor, pParam->largeMotor); auto* controller = Common::Singleton<Input::GameController>::Instance(); controller->SetVibration(pParam->smallMotor, pParam->largeMotor); return ORBIS_OK; } return ORBIS_PAD_ERROR_INVALID_ARG; } int PS4_SYSV_ABI scePadSetVibrationForce() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSetVrTrackingMode() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadShareOutputData() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadStartRecording() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadStopRecording() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadSwitchConnection() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadVertualDeviceAddDevice() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadVirtualDeviceAddDevice() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadVirtualDeviceDeleteDevice() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadVirtualDeviceDisableButtonRemapping() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadVirtualDeviceGetRemoteSetting() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI scePadVirtualDeviceInsertData() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_28B998C7D8A3DA1D() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_298D21481F94C9FA() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_51E514BCD3A05CA5() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_89C9237E393DA243() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_EF103E845B6F0420() { LOG_ERROR(Lib_Pad, "(STUBBED) called"); return ORBIS_OK; } void RegisterlibScePad(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("6ncge5+l5Qs", "libScePad", 1, "libScePad", 1, 1, scePadClose); LIB_FUNCTION("kazv1NzSB8c", "libScePad", 1, "libScePad", 1, 1, scePadConnectPort); LIB_FUNCTION("AcslpN1jHR8", "libScePad", 1, "libScePad", 1, 1, scePadDeviceClassGetExtendedInformation); LIB_FUNCTION("IHPqcbc0zCA", "libScePad", 1, "libScePad", 1, 1, scePadDeviceClassParseData); LIB_FUNCTION("d7bXuEBycDI", "libScePad", 1, "libScePad", 1, 1, scePadDeviceOpen); LIB_FUNCTION("0aziJjRZxqQ", "libScePad", 1, "libScePad", 1, 1, scePadDisableVibration); LIB_FUNCTION("pnZXireDoeI", "libScePad", 1, "libScePad", 1, 1, scePadDisconnectDevice); LIB_FUNCTION("9ez71nWSvD0", "libScePad", 1, "libScePad", 1, 1, scePadDisconnectPort); LIB_FUNCTION("77ooWxGOIVs", "libScePad", 1, "libScePad", 1, 1, scePadEnableAutoDetect); LIB_FUNCTION("+cE4Jx431wc", "libScePad", 1, "libScePad", 1, 1, scePadEnableExtensionPort); LIB_FUNCTION("E1KEw5XMGQQ", "libScePad", 1, "libScePad", 1, 1, scePadEnableSpecificDeviceClass); LIB_FUNCTION("DD-KiRLBqkQ", "libScePad", 1, "libScePad", 1, 1, scePadEnableUsbConnection); LIB_FUNCTION("Q66U8FdrMaw", "libScePad", 1, "libScePad", 1, 1, scePadGetBluetoothAddress); LIB_FUNCTION("qtasqbvwgV4", "libScePad", 1, "libScePad", 1, 1, scePadGetCapability); LIB_FUNCTION("gjP9-KQzoUk", "libScePad", 1, "libScePad", 1, 1, scePadGetControllerInformation); LIB_FUNCTION("Uq6LgTJEmQs", "libScePad", 1, "libScePad", 1, 1, scePadGetDataInternal); LIB_FUNCTION("hDgisSGkOgw", "libScePad", 1, "libScePad", 1, 1, scePadGetDeviceId); LIB_FUNCTION("4rS5zG7RFaM", "libScePad", 1, "libScePad", 1, 1, scePadGetDeviceInfo); LIB_FUNCTION("hGbf2QTBmqc", "libScePad", 1, "libScePad", 1, 1, scePadGetExtControllerInformation); LIB_FUNCTION("1DmZjZAuzEM", "libScePad", 1, "libScePad", 1, 1, scePadGetExtensionUnitInfo); LIB_FUNCTION("PZSoY8j0Pko", "libScePad", 1, "libScePad", 1, 1, scePadGetFeatureReport); LIB_FUNCTION("u1GRHp+oWoY", "libScePad", 1, "libScePad", 1, 1, scePadGetHandle); LIB_FUNCTION("kiA9bZhbnAg", "libScePad", 1, "libScePad", 1, 1, scePadGetIdleCount); LIB_FUNCTION("1Odcw19nADw", "libScePad", 1, "libScePad", 1, 1, scePadGetInfo); LIB_FUNCTION("4x5Im8pr0-4", "libScePad", 1, "libScePad", 1, 1, scePadGetInfoByPortType); LIB_FUNCTION("vegw8qax5MI", "libScePad", 1, "libScePad", 1, 1, scePadGetLicenseControllerInformation); LIB_FUNCTION("WPIB7zBWxVE", "libScePad", 1, "libScePad", 1, 1, scePadGetMotionSensorPosition); LIB_FUNCTION("k4+nDV9vbT0", "libScePad", 1, "libScePad", 1, 1, scePadGetMotionTimerUnit); LIB_FUNCTION("do-JDWX+zRs", "libScePad", 1, "libScePad", 1, 1, scePadGetSphereRadius); LIB_FUNCTION("QuOaoOcSOw0", "libScePad", 1, "libScePad", 1, 1, scePadGetVersionInfo); LIB_FUNCTION("hv1luiJrqQM", "libScePad", 1, "libScePad", 1, 1, scePadInit); LIB_FUNCTION("bi0WNvZ1nug", "libScePad", 1, "libScePad", 1, 1, scePadIsBlasterConnected); LIB_FUNCTION("mEC+xJKyIjQ", "libScePad", 1, "libScePad", 1, 1, scePadIsDS4Connected); LIB_FUNCTION("d2Qk-i8wGak", "libScePad", 1, "libScePad", 1, 1, scePadIsLightBarBaseBrightnessControllable); LIB_FUNCTION("4y9RNPSBsqg", "libScePad", 1, "libScePad", 1, 1, scePadIsMoveConnected); LIB_FUNCTION("9e56uLgk5y0", "libScePad", 1, "libScePad", 1, 1, scePadIsMoveReproductionModel); LIB_FUNCTION("pFTi-yOrVeQ", "libScePad", 1, "libScePad", 1, 1, scePadIsValidHandle); LIB_FUNCTION("CfwUlQtCFi4", "libScePad", 1, "libScePad", 1, 1, scePadMbusInit); LIB_FUNCTION("s7CvzS+9ZIs", "libScePad", 1, "libScePad", 1, 1, scePadMbusTerm); LIB_FUNCTION("xk0AcarP3V4", "libScePad", 1, "libScePad", 1, 1, scePadOpen); LIB_FUNCTION("WFIiSfXGUq8", "libScePad", 1, "libScePad", 1, 1, scePadOpenExt); LIB_FUNCTION("71E9e6n+2R8", "libScePad", 1, "libScePad", 1, 1, scePadOpenExt2); LIB_FUNCTION("DrUu8cPrje8", "libScePad", 1, "libScePad", 1, 1, scePadOutputReport); LIB_FUNCTION("q1cHNfGycLI", "libScePad", 1, "libScePad", 1, 1, scePadRead); LIB_FUNCTION("fm1r2vv5+OU", "libScePad", 1, "libScePad", 1, 1, scePadReadBlasterForTracker); LIB_FUNCTION("QjwkT2Ycmew", "libScePad", 1, "libScePad", 1, 1, scePadReadExt); LIB_FUNCTION("2NhkFTRnXHk", "libScePad", 1, "libScePad", 1, 1, scePadReadForTracker); LIB_FUNCTION("3u4M8ck9vJM", "libScePad", 1, "libScePad", 1, 1, scePadReadHistory); LIB_FUNCTION("YndgXqQVV7c", "libScePad", 1, "libScePad", 1, 1, scePadReadState); LIB_FUNCTION("5Wf4q349s+Q", "libScePad", 1, "libScePad", 1, 1, scePadReadStateExt); LIB_FUNCTION("DscD1i9HX1w", "libScePad", 1, "libScePad", 1, 1, scePadResetLightBar); LIB_FUNCTION("+4c9xRLmiXQ", "libScePad", 1, "libScePad", 1, 1, scePadResetLightBarAll); LIB_FUNCTION("+Yp6+orqf1M", "libScePad", 1, "libScePad", 1, 1, scePadResetLightBarAllByPortType); LIB_FUNCTION("rIZnR6eSpvk", "libScePad", 1, "libScePad", 1, 1, scePadResetOrientation); LIB_FUNCTION("jbAqAvLEP4A", "libScePad", 1, "libScePad", 1, 1, scePadResetOrientationForTracker); LIB_FUNCTION("r44mAxdSG+U", "libScePad", 1, "libScePad", 1, 1, scePadSetAngularVelocityDeadbandState); LIB_FUNCTION("ew647HuKi2Y", "libScePad", 1, "libScePad", 1, 1, scePadSetAutoPowerOffCount); LIB_FUNCTION("MbTt1EHYCTg", "libScePad", 1, "libScePad", 1, 1, scePadSetButtonRemappingInfo); LIB_FUNCTION("MLA06oNfF+4", "libScePad", 1, "libScePad", 1, 1, scePadSetConnection); LIB_FUNCTION("bsbHFI0bl5s", "libScePad", 1, "libScePad", 1, 1, scePadSetExtensionReport); LIB_FUNCTION("xqgVCEflEDY", "libScePad", 1, "libScePad", 1, 1, scePadSetFeatureReport); LIB_FUNCTION("lrjFx4xWnY8", "libScePad", 1, "libScePad", 1, 1, scePadSetForceIntercepted); LIB_FUNCTION("RR4novUEENY", "libScePad", 1, "libScePad", 1, 1, scePadSetLightBar); LIB_FUNCTION("dhQXEvmrVNQ", "libScePad", 1, "libScePad", 1, 1, scePadSetLightBarBaseBrightness); LIB_FUNCTION("etaQhgPHDRY", "libScePad", 1, "libScePad", 1, 1, scePadSetLightBarBlinking); LIB_FUNCTION("iHuOWdvQVpg", "libScePad", 1, "libScePad", 1, 1, scePadSetLightBarForTracker); LIB_FUNCTION("o-6Y99a8dKU", "libScePad", 1, "libScePad", 1, 1, scePadSetLoginUserNumber); LIB_FUNCTION("clVvL4ZDntw", "libScePad", 1, "libScePad", 1, 1, scePadSetMotionSensorState); LIB_FUNCTION("flYYxek1wy8", "libScePad", 1, "libScePad", 1, 1, scePadSetProcessFocus); LIB_FUNCTION("DmBx8K+jDWw", "libScePad", 1, "libScePad", 1, 1, scePadSetProcessPrivilege); LIB_FUNCTION("FbxEpTRDou8", "libScePad", 1, "libScePad", 1, 1, scePadSetProcessPrivilegeOfButtonRemapping); LIB_FUNCTION("yah8Bk4TcYY", "libScePad", 1, "libScePad", 1, 1, scePadSetShareButtonMaskForRemotePlay); LIB_FUNCTION("vDLMoJLde8I", "libScePad", 1, "libScePad", 1, 1, scePadSetTiltCorrectionState); LIB_FUNCTION("z+GEemoTxOo", "libScePad", 1, "libScePad", 1, 1, scePadSetUserColor); LIB_FUNCTION("yFVnOdGxvZY", "libScePad", 1, "libScePad", 1, 1, scePadSetVibration); LIB_FUNCTION("8BOObG94-tc", "libScePad", 1, "libScePad", 1, 1, scePadSetVibrationForce); LIB_FUNCTION("--jrY4SHfm8", "libScePad", 1, "libScePad", 1, 1, scePadSetVrTrackingMode); LIB_FUNCTION("zFJ35q3RVnY", "libScePad", 1, "libScePad", 1, 1, scePadShareOutputData); LIB_FUNCTION("80XdmVYsNPA", "libScePad", 1, "libScePad", 1, 1, scePadStartRecording); LIB_FUNCTION("gAHvg6JPIic", "libScePad", 1, "libScePad", 1, 1, scePadStopRecording); LIB_FUNCTION("Oi7FzRWFr0Y", "libScePad", 1, "libScePad", 1, 1, scePadSwitchConnection); LIB_FUNCTION("0MB5x-ieRGI", "libScePad", 1, "libScePad", 1, 1, scePadVertualDeviceAddDevice); LIB_FUNCTION("N7tpsjWQ87s", "libScePad", 1, "libScePad", 1, 1, scePadVirtualDeviceAddDevice); LIB_FUNCTION("PFec14-UhEQ", "libScePad", 1, "libScePad", 1, 1, scePadVirtualDeviceDeleteDevice); LIB_FUNCTION("pjPCronWdxI", "libScePad", 1, "libScePad", 1, 1, scePadVirtualDeviceDisableButtonRemapping); LIB_FUNCTION("LKXfw7VJYqg", "libScePad", 1, "libScePad", 1, 1, scePadVirtualDeviceGetRemoteSetting); LIB_FUNCTION("IWOyO5jKuZg", "libScePad", 1, "libScePad", 1, 1, scePadVirtualDeviceInsertData); LIB_FUNCTION("KLmYx9ij2h0", "libScePad", 1, "libScePad", 1, 1, Func_28B998C7D8A3DA1D); LIB_FUNCTION("KY0hSB+Uyfo", "libScePad", 1, "libScePad", 1, 1, Func_298D21481F94C9FA); LIB_FUNCTION("UeUUvNOgXKU", "libScePad", 1, "libScePad", 1, 1, Func_51E514BCD3A05CA5); LIB_FUNCTION("ickjfjk9okM", "libScePad", 1, "libScePad", 1, 1, Func_89C9237E393DA243); LIB_FUNCTION("7xA+hFtvBCA", "libScePad", 1, "libScePad", 1, 1, Func_EF103E845B6F0420); }; } // namespace Libraries::Pad
26,894
C++
.cpp
622
38.430868
100
0.688589
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,565
random.cpp
shadps4-emu_shadPS4/src/core/libraries/random/random.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "random.h" #include "random_error.h" #include "common/logging/log.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" namespace Libraries::Random { s32 PS4_SYSV_ABI sceRandomGetRandomNumber(u8* buf, std::size_t size) { LOG_TRACE(Lib_Random, "called"); if (size > SCE_RANDOM_MAX_SIZE) { return SCE_RANDOM_ERROR_INVALID; } for (auto i = 0; i < size; ++i) { buf[i] = std::rand() & 0xFF; } return ORBIS_OK; } void RegisterlibSceRandom(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("PI7jIZj4pcE", "libSceRandom", 1, "libSceRandom", 1, 1, sceRandomGetRandomNumber); }; } // namespace Libraries::Random
797
C++
.cpp
22
32.909091
99
0.708333
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,566
shareplay.cpp
shadps4-emu_shadPS4/src/core/libraries/share_play/shareplay.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "shareplay.h" #include "common/logging/log.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" namespace Libraries::SharePlay { int PS4_SYSV_ABI sceSharePlayCrashDaemon() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayGetCurrentConnectionInfo(OrbisSharePlayConnectionInfo* pInfo) { memset(pInfo, 0, sizeof(*pInfo)); pInfo->status = ORBIS_SHARE_PLAY_CONNECTION_STATUS_DORMANT; LOG_DEBUG(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayGetCurrentConnectionInfoA() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayGetCurrentInfo() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayGetEvent() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayInitialize() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayNotifyDialogOpen() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayNotifyForceCloseForCdlg() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayNotifyOpenQuickMenu() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayResumeScreenForCdlg() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayServerLock() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayServerUnLock() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlaySetMode() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlaySetProhibition() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlaySetProhibitionModeWithAppId() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayStartStandby() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayStartStreaming() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayStopStandby() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayStopStreaming() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceSharePlayTerminate() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_2E93C0EA6A6B67C4() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_C1C236728D88E177() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_E9E80C474781F115() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_F3DD6199DA15ED44() { LOG_ERROR(Lib_SharePlay, "(STUBBED) called"); return ORBIS_OK; } void RegisterlibSceSharePlay(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("ggnCfalLU-8", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayCrashDaemon); LIB_FUNCTION("OOrLKB0bSDs", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayGetCurrentConnectionInfo); LIB_FUNCTION("+MCXJlWdi+s", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayGetCurrentConnectionInfoA); LIB_FUNCTION("vUMkWXQff3w", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayGetCurrentInfo); LIB_FUNCTION("Md7Mdkr8LBc", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayGetEvent); LIB_FUNCTION("isruqthpYcw", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayInitialize); LIB_FUNCTION("9zwJpai7jGc", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayNotifyDialogOpen); LIB_FUNCTION("VUW2V9cUTP4", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayNotifyForceCloseForCdlg); LIB_FUNCTION("XL0WwUJoQPg", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayNotifyOpenQuickMenu); LIB_FUNCTION("6-1fKaa5HlY", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayResumeScreenForCdlg); LIB_FUNCTION("U28jAuLHj6c", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayServerLock); LIB_FUNCTION("3Oaux9ITEtY", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayServerUnLock); LIB_FUNCTION("QZy+KmyqKPU", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlaySetMode); LIB_FUNCTION("co2NCj--pnc", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlaySetProhibition); LIB_FUNCTION("KADsbjNCgPo", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlaySetProhibitionModeWithAppId); LIB_FUNCTION("-F6NddfUsa4", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayStartStandby); LIB_FUNCTION("rWVNHNnEx6g", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayStartStreaming); LIB_FUNCTION("zEDkUWLVwFI", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayStopStandby); LIB_FUNCTION("aGlema+JxUU", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayStopStreaming); LIB_FUNCTION("UaLjloJinow", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, sceSharePlayTerminate); LIB_FUNCTION("LpPA6mprZ8Q", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, Func_2E93C0EA6A6B67C4); LIB_FUNCTION("wcI2co2I4Xc", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, Func_C1C236728D88E177); LIB_FUNCTION("6egMR0eB8RU", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, Func_E9E80C474781F115); LIB_FUNCTION("891hmdoV7UQ", "libSceSharePlay", 1, "libSceSharePlay", 0, 0, Func_F3DD6199DA15ED44); LIB_FUNCTION("OOrLKB0bSDs", "libSceSharePlayCompat", 1, "libSceSharePlay", 0, 0, sceSharePlayGetCurrentConnectionInfo); }; } // namespace Libraries::SharePlay
6,568
C++
.cpp
157
36.146497
100
0.698574
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,567
gamelivestreaming.cpp
shadps4-emu_shadPS4/src/core/libraries/game_live_streaming/gamelivestreaming.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "gamelivestreaming.h" #include "common/logging/log.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" namespace Libraries::GameLiveStreaming { int PS4_SYSV_ABI sceGameLiveStreamingStartDebugBroadcast() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingStopDebugBroadcast() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingApplySocialFeedbackMessageFilter() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingCheckCallback() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingClearPresetSocialFeedbackCommands() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingClearSocialFeedbackMessages() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingClearSpoilerTag() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingEnableLiveStreaming() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingEnableSocialFeedback() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingGetCurrentBroadcastScreenLayout() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingGetCurrentStatus(OrbisGameLiveStreamingStatus* status) { memset(status, 0, sizeof(*status)); status->isOnAir = false; LOG_DEBUG(Lib_GameLiveStreaming, "(STUBBED) called userid = {}", status->userId); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingGetCurrentStatus2() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingGetProgramInfo() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingGetSocialFeedbackMessages() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingGetSocialFeedbackMessagesCount() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingInitialize() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingLaunchLiveViewer() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingLaunchLiveViewerA() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingPermitLiveStreaming() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingPermitServerSideRecording() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingPostSocialMessage() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingRegisterCallback() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingScreenCloseSeparateMode() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingScreenConfigureSeparateMode() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingScreenInitialize() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingScreenInitializeSeparateModeParameter() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingScreenOpenSeparateMode() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingScreenSetMode() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingScreenTerminate() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetCameraFrameSetting() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetDefaultServiceProviderPermission() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetGuardAreas() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetInvitationSessionId() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetLinkCommentPreset() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetMaxBitrate() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetMetadata() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetPresetSocialFeedbackCommands() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetPresetSocialFeedbackCommandsDescription() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetServiceProviderPermission() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetSpoilerTag() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingSetStandbyScreenResource() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingStartGenerateStandbyScreenResource() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingStartSocialFeedbackMessageFiltering() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingStopGenerateStandbyScreenResource() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingStopSocialFeedbackMessageFiltering() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingTerminate() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceGameLiveStreamingUnregisterCallback() { LOG_ERROR(Lib_GameLiveStreaming, "(STUBBED) called"); return ORBIS_OK; } void RegisterlibSceGameLiveStreaming(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("caqgDl+V9qA", "libSceGameLiveStreaming_debug", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingStartDebugBroadcast); LIB_FUNCTION("0i8Lrllxwow", "libSceGameLiveStreaming_debug", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingStopDebugBroadcast); LIB_FUNCTION("NqkTzemliC0", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingApplySocialFeedbackMessageFilter); LIB_FUNCTION("PC4jq87+YQI", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingCheckCallback); LIB_FUNCTION("FcHBfHjFXkA", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingClearPresetSocialFeedbackCommands); LIB_FUNCTION("lZ2Sd0uEvpo", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingClearSocialFeedbackMessages); LIB_FUNCTION("6c2zGtThFww", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingClearSpoilerTag); LIB_FUNCTION("dWM80AX39o4", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingEnableLiveStreaming); LIB_FUNCTION("wBOQWjbWMfU", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingEnableSocialFeedback); LIB_FUNCTION("aRSQNqbats4", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingGetCurrentBroadcastScreenLayout); LIB_FUNCTION("CoPMx369EqM", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingGetCurrentStatus); LIB_FUNCTION("lK8dLBNp9OE", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingGetCurrentStatus2); LIB_FUNCTION("OIIm19xu+NM", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingGetProgramInfo); LIB_FUNCTION("PMx7N4WqNdo", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingGetSocialFeedbackMessages); LIB_FUNCTION("yeQKjHETi40", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingGetSocialFeedbackMessagesCount); LIB_FUNCTION("kvYEw2lBndk", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingInitialize); LIB_FUNCTION("ysWfX5PPbfc", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingLaunchLiveViewer); LIB_FUNCTION("cvRCb7DTAig", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingLaunchLiveViewerA); LIB_FUNCTION("K0QxEbD7q+c", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingPermitLiveStreaming); LIB_FUNCTION("-EHnU68gExU", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingPermitServerSideRecording); LIB_FUNCTION("hggKhPySVgI", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingPostSocialMessage); LIB_FUNCTION("nFP8qT9YXbo", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingRegisterCallback); LIB_FUNCTION("b5RaMD2J0So", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingScreenCloseSeparateMode); LIB_FUNCTION("hBdd8n6kuvE", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingScreenConfigureSeparateMode); LIB_FUNCTION("uhCmn81s-mU", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingScreenInitialize); LIB_FUNCTION("fo5B8RUaBxQ", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingScreenInitializeSeparateModeParameter); LIB_FUNCTION("iorzW0pKOiA", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingScreenOpenSeparateMode); LIB_FUNCTION("gDSvt78H3Oo", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingScreenSetMode); LIB_FUNCTION("HE93dr-5rx4", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingScreenTerminate); LIB_FUNCTION("3PSiwAzFISE", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetCameraFrameSetting); LIB_FUNCTION("TwuUzTKKeek", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetDefaultServiceProviderPermission); LIB_FUNCTION("Gw6S4oqlY7E", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetGuardAreas); LIB_FUNCTION("QmQYwQ7OTJI", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetInvitationSessionId); LIB_FUNCTION("Sb5bAXyUt5c", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetLinkCommentPreset); LIB_FUNCTION("q-kxuaF7URU", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetMaxBitrate); LIB_FUNCTION("hUY-mSOyGL0", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetMetadata); LIB_FUNCTION("ycodiP2I0xo", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetPresetSocialFeedbackCommands); LIB_FUNCTION("x6deXUpQbBo", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetPresetSocialFeedbackCommandsDescription); LIB_FUNCTION("mCoz3k3zPmA", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetServiceProviderPermission); LIB_FUNCTION("ZuX+zzz2DkA", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetSpoilerTag); LIB_FUNCTION("MLvYI86FFAo", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingSetStandbyScreenResource); LIB_FUNCTION("y0KkAydy9xE", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingStartGenerateStandbyScreenResource); LIB_FUNCTION("Y1WxX7dPMCw", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingStartSocialFeedbackMessageFiltering); LIB_FUNCTION("D7dg5QJ4FlE", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingStopGenerateStandbyScreenResource); LIB_FUNCTION("bYuGUBuIsaY", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingStopSocialFeedbackMessageFiltering); LIB_FUNCTION("9yK6Fk8mKOQ", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingTerminate); LIB_FUNCTION("5XHaH3kL+bA", "libSceGameLiveStreaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingUnregisterCallback); LIB_FUNCTION("caqgDl+V9qA", "libSceGameLiveStreaming_direct_streaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingStartDebugBroadcast); LIB_FUNCTION("0i8Lrllxwow", "libSceGameLiveStreaming_direct_streaming", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingStopDebugBroadcast); LIB_FUNCTION("CoPMx369EqM", "libSceGameLiveStreamingCompat", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingGetCurrentStatus); LIB_FUNCTION("ysWfX5PPbfc", "libSceGameLiveStreamingCompat", 1, "libSceGameLiveStreaming", 1, 1, sceGameLiveStreamingLaunchLiveViewer); }; } // namespace Libraries::GameLiveStreaming
15,464
C++
.cpp
302
45.218543
100
0.750248
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,568
trophy_ui.cpp
shadps4-emu_shadPS4/src/core/libraries/np_trophy/trophy_ui.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <chrono> #include <mutex> #include <imgui.h> #include "common/assert.h" #include "common/singleton.h" #include "imgui/imgui_std.h" #include "trophy_ui.h" using namespace ImGui; namespace Libraries::NpTrophy { std::optional<TrophyUI> current_trophy_ui; std::queue<TrophyInfo> trophy_queue; std::mutex queueMtx; TrophyUI::TrophyUI(const std::filesystem::path& trophyIconPath, const std::string& trophyName) : trophy_name(trophyName) { if (std::filesystem::exists(trophyIconPath)) { trophy_icon = RefCountedTexture::DecodePngFile(trophyIconPath); } else { LOG_ERROR(Lib_NpTrophy, "Couldnt load trophy icon at {}", fmt::UTF(trophyIconPath.u8string())); } AddLayer(this); } TrophyUI::~TrophyUI() { Finish(); } void TrophyUI::Finish() { RemoveLayer(this); } void TrophyUI::Draw() { const auto& io = GetIO(); const ImVec2 window_size{ std::min(io.DisplaySize.x, 250.f), std::min(io.DisplaySize.y, 70.f), }; SetNextWindowSize(window_size); SetNextWindowCollapsed(false); SetNextWindowPos(ImVec2(io.DisplaySize.x - 250, 50)); KeepNavHighlight(); if (Begin("Trophy Window", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoInputs)) { if (trophy_icon) { Image(trophy_icon.GetTexture().im_id, ImVec2(50, 50)); ImGui::SameLine(); } else { // placeholder const auto pos = GetCursorScreenPos(); ImGui::GetWindowDrawList()->AddRectFilled(pos, pos + ImVec2{50.0f}, GetColorU32(ImVec4{0.7f})); ImGui::Indent(60); } TextWrapped("Trophy earned!\n%s", trophy_name.c_str()); } End(); trophy_timer -= io.DeltaTime; if (trophy_timer <= 0) { std::lock_guard<std::mutex> lock(queueMtx); if (!trophy_queue.empty()) { TrophyInfo next_trophy = trophy_queue.front(); trophy_queue.pop(); current_trophy_ui.emplace(next_trophy.trophy_icon_path, next_trophy.trophy_name); } else { current_trophy_ui.reset(); } } } void AddTrophyToQueue(const std::filesystem::path& trophyIconPath, const std::string& trophyName) { std::lock_guard<std::mutex> lock(queueMtx); if (current_trophy_ui.has_value()) { TrophyInfo new_trophy; new_trophy.trophy_icon_path = trophyIconPath; new_trophy.trophy_name = trophyName; trophy_queue.push(new_trophy); } else { current_trophy_ui.emplace(trophyIconPath, trophyName); } } } // namespace Libraries::NpTrophy
2,837
C++
.cpp
80
28.6125
99
0.641166
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,569
np_trophy.cpp
shadps4-emu_shadPS4/src/core/libraries/np_trophy/np_trophy.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <unordered_map> #include <pugixml.hpp> #include "common/logging/log.h" #include "common/path_util.h" #include "common/slot_vector.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" #include "np_trophy.h" #include "trophy_ui.h" namespace Libraries::NpTrophy { std::string game_serial; static constexpr auto MaxTrophyHandles = 4u; static constexpr auto MaxTrophyContexts = 8u; using ContextKey = std::pair<u32, u32>; // <user_id, service label> struct ContextKeyHash { size_t operator()(const ContextKey& key) const { return key.first + (u64(key.second) << 32u); } }; struct TrophyContext { u32 context_id; }; static Common::SlotVector<OrbisNpTrophyHandle> trophy_handles{}; static Common::SlotVector<ContextKey> trophy_contexts{}; static std::unordered_map<ContextKey, TrophyContext, ContextKeyHash> contexts_internal{}; void ORBIS_NP_TROPHY_FLAG_ZERO(OrbisNpTrophyFlagArray* p) { for (int i = 0; i < ORBIS_NP_TROPHY_NUM_MAX; i++) { uint32_t array_index = i / 32; uint32_t bit_position = i % 32; p->flag_bits[array_index] &= ~(1U << bit_position); } } void ORBIS_NP_TROPHY_FLAG_SET(int32_t trophyId, OrbisNpTrophyFlagArray* p) { uint32_t array_index = trophyId / 32; uint32_t bit_position = trophyId % 32; p->flag_bits[array_index] |= (1U << bit_position); } void ORBIS_NP_TROPHY_FLAG_SET_ALL(OrbisNpTrophyFlagArray* p) { for (int i = 0; i < ORBIS_NP_TROPHY_NUM_MAX; i++) { uint32_t array_index = i / 32; uint32_t bit_position = i % 32; p->flag_bits[array_index] |= (1U << bit_position); } } void ORBIS_NP_TROPHY_FLAG_CLR(int32_t trophyId, OrbisNpTrophyFlagArray* p) { uint32_t array_index = trophyId / 32; uint32_t bit_position = trophyId % 32; p->flag_bits[array_index] &= ~(1U << bit_position); } bool ORBIS_NP_TROPHY_FLAG_ISSET(int32_t trophyId, OrbisNpTrophyFlagArray* p) { uint32_t array_index = trophyId / 32; uint32_t bit_position = trophyId % 32; return (p->flag_bits[array_index] & (1U << bit_position)) ? 1 : 0; } OrbisNpTrophyGrade GetTrophyGradeFromChar(char trophyType) { switch (trophyType) { default: return ORBIS_NP_TROPHY_GRADE_UNKNOWN; break; case 'B': return ORBIS_NP_TROPHY_GRADE_BRONZE; break; case 'S': return ORBIS_NP_TROPHY_GRADE_SILVER; break; case 'G': return ORBIS_NP_TROPHY_GRADE_GOLD; break; case 'P': return ORBIS_NP_TROPHY_GRADE_PLATINUM; break; } } int PS4_SYSV_ABI sceNpTrophyAbortHandle(OrbisNpTrophyHandle handle) { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyCaptureScreenshot() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyConfigGetTrophyDetails() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyConfigGetTrophyFlagArray() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyConfigGetTrophyGroupArray() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyConfigGetTrophyGroupDetails() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyConfigGetTrophySetInfo() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyConfigGetTrophySetInfoInGroup() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyConfigGetTrophySetVersion() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyConfigGetTrophyTitleDetails() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyConfigHasGroupFeature() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } s32 PS4_SYSV_ABI sceNpTrophyCreateContext(OrbisNpTrophyContext* context, int32_t user_id, uint32_t service_label, uint64_t options) { ASSERT(options == 0ull); if (!context) { return ORBIS_NP_TROPHY_ERROR_INVALID_ARGUMENT; } if (trophy_contexts.size() >= MaxTrophyContexts) { return ORBIS_NP_TROPHY_ERROR_CONTEXT_EXCEEDS_MAX; } const auto& key = ContextKey{user_id, service_label}; if (contexts_internal.contains(key)) { return ORBIS_NP_TROPHY_ERROR_CONTEXT_ALREADY_EXISTS; } const auto ctx_id = trophy_contexts.insert(user_id, service_label); contexts_internal[key].context_id = ctx_id.index; LOG_INFO(Lib_NpTrophy, "New context = {}, user_id = {} service label = {}", ctx_id.index, user_id, service_label); *context = ctx_id.index; return ORBIS_OK; } s32 PS4_SYSV_ABI sceNpTrophyCreateHandle(OrbisNpTrophyHandle* handle) { if (!handle) { return ORBIS_NP_TROPHY_ERROR_INVALID_ARGUMENT; } if (trophy_handles.size() >= MaxTrophyHandles) { return ORBIS_NP_TROPHY_ERROR_HANDLE_EXCEEDS_MAX; } const auto handle_id = trophy_handles.insert(); LOG_INFO(Lib_NpTrophy, "New handle = {}", handle_id.index); *handle = handle_id.index; return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyDestroyContext(OrbisNpTrophyContext context) { LOG_INFO(Lib_NpTrophy, "Destroyed Context {}", context); if (context == ORBIS_NP_TROPHY_INVALID_CONTEXT) return ORBIS_NP_TROPHY_ERROR_INVALID_CONTEXT; Common::SlotId contextId; contextId.index = context; ContextKey contextkey = trophy_contexts[contextId]; trophy_contexts.erase(contextId); contexts_internal.erase(contextkey); return ORBIS_OK; } s32 PS4_SYSV_ABI sceNpTrophyDestroyHandle(OrbisNpTrophyHandle handle) { if (handle == ORBIS_NP_TROPHY_INVALID_HANDLE) return ORBIS_NP_TROPHY_ERROR_INVALID_HANDLE; if (!trophy_handles.is_allocated({static_cast<u32>(handle)})) { return ORBIS_NP_TROPHY_ERROR_INVALID_HANDLE; } trophy_handles.erase({static_cast<u32>(handle)}); LOG_INFO(Lib_NpTrophy, "Handle {} destroyed", handle); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyGetGameIcon(OrbisNpTrophyContext context, OrbisNpTrophyHandle handle, void* buffer, size_t* size) { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } struct GameTrophyInfo { uint32_t num_groups; uint32_t num_trophies; uint32_t num_trophies_by_rarity[5]; uint32_t unlocked_trophies; uint32_t unlocked_trophies_by_rarity[5]; }; int PS4_SYSV_ABI sceNpTrophyGetGameInfo(OrbisNpTrophyContext context, OrbisNpTrophyHandle handle, OrbisNpTrophyGameDetails* details, OrbisNpTrophyGameData* data) { LOG_INFO(Lib_NpTrophy, "Getting Game Trophy"); if (context == ORBIS_NP_TROPHY_INVALID_CONTEXT) return ORBIS_NP_TROPHY_ERROR_INVALID_CONTEXT; if (handle == ORBIS_NP_TROPHY_INVALID_HANDLE) return ORBIS_NP_TROPHY_ERROR_INVALID_HANDLE; if (details == nullptr || data == nullptr) return ORBIS_NP_TROPHY_ERROR_INVALID_ARGUMENT; if (details->size != 0x4A0 || data->size != 0x20) return ORBIS_NP_TROPHY_ERROR_INVALID_ARGUMENT; const auto trophy_dir = Common::FS::GetUserPath(Common::FS::PathType::MetaDataDir) / game_serial / "TrophyFiles"; auto trophy_file = trophy_dir / "trophy00" / "Xml" / "TROP.XML"; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(trophy_file.native().c_str()); if (!result) { LOG_ERROR(Lib_NpTrophy, "Failed to parse trophy xml : {}", result.description()); return ORBIS_OK; } GameTrophyInfo game_info{}; auto trophyconf = doc.child("trophyconf"); for (const pugi::xml_node& node : trophyconf.children()) { std::string_view node_name = node.name(); if (node_name == "title-name") { strncpy(details->title, node.text().as_string(), ORBIS_NP_TROPHY_GAME_TITLE_MAX_SIZE); } if (node_name == "title-detail") { strncpy(details->description, node.text().as_string(), ORBIS_NP_TROPHY_GAME_DESCR_MAX_SIZE); } if (node_name == "group") game_info.num_groups++; if (node_name == "trophy") { bool current_trophy_unlockstate = node.attribute("unlockstate").as_bool(); std::string_view current_trophy_grade = node.attribute("ttype").value(); if (current_trophy_grade.empty()) { continue; } game_info.num_trophies++; int trophy_grade = GetTrophyGradeFromChar(current_trophy_grade.at(0)); game_info.num_trophies_by_rarity[trophy_grade]++; if (current_trophy_unlockstate) { game_info.unlocked_trophies++; game_info.unlocked_trophies_by_rarity[trophy_grade]++; } } } details->num_groups = game_info.num_groups; details->num_trophies = game_info.num_trophies; details->num_platinum = game_info.num_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_PLATINUM]; details->num_gold = game_info.num_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_GOLD]; details->num_silver = game_info.num_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_SILVER]; details->num_bronze = game_info.num_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_BRONZE]; data->unlocked_trophies = game_info.unlocked_trophies; data->unlocked_platinum = game_info.unlocked_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_PLATINUM]; data->unlocked_gold = game_info.unlocked_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_GOLD]; data->unlocked_silver = game_info.unlocked_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_SILVER]; data->unlocked_bronze = game_info.unlocked_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_BRONZE]; // maybe this should be 1 instead of 100? data->progress_percentage = 100; return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyGetGroupIcon(OrbisNpTrophyContext context, OrbisNpTrophyHandle handle, OrbisNpTrophyGroupId groupId, void* buffer, size_t* size) { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } struct GroupTrophyInfo { uint32_t num_trophies; uint32_t num_trophies_by_rarity[5]; uint32_t unlocked_trophies; uint32_t unlocked_trophies_by_rarity[5]; }; int PS4_SYSV_ABI sceNpTrophyGetGroupInfo(OrbisNpTrophyContext context, OrbisNpTrophyHandle handle, OrbisNpTrophyGroupId groupId, OrbisNpTrophyGroupDetails* details, OrbisNpTrophyGroupData* data) { LOG_INFO(Lib_NpTrophy, "Getting Trophy Group Info for id {}", groupId); if (context == ORBIS_NP_TROPHY_INVALID_CONTEXT) return ORBIS_NP_TROPHY_ERROR_INVALID_CONTEXT; if (handle == ORBIS_NP_TROPHY_INVALID_HANDLE) return ORBIS_NP_TROPHY_ERROR_INVALID_HANDLE; if (details == nullptr || data == nullptr) return ORBIS_NP_TROPHY_ERROR_INVALID_ARGUMENT; if (details->size != 0x4A0 || data->size != 0x28) return ORBIS_NP_TROPHY_ERROR_INVALID_ARGUMENT; const auto trophy_dir = Common::FS::GetUserPath(Common::FS::PathType::MetaDataDir) / game_serial / "TrophyFiles"; auto trophy_file = trophy_dir / "trophy00" / "Xml" / "TROP.XML"; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(trophy_file.native().c_str()); if (!result) { LOG_ERROR(Lib_NpTrophy, "Failed to open trophy xml : {}", result.description()); return ORBIS_OK; } GroupTrophyInfo group_info{}; auto trophyconf = doc.child("trophyconf"); for (const pugi::xml_node& node : trophyconf.children()) { std::string_view node_name = node.name(); if (node_name == "group") { int current_group_id = node.attribute("id").as_int(ORBIS_NP_TROPHY_INVALID_GROUP_ID); if (current_group_id != ORBIS_NP_TROPHY_INVALID_GROUP_ID) { if (current_group_id == groupId) { std::string_view current_group_name = node.child("name").text().as_string(); std::string_view current_group_description = node.child("detail").text().as_string(); strncpy(details->title, current_group_name.data(), ORBIS_NP_TROPHY_GROUP_TITLE_MAX_SIZE); strncpy(details->description, current_group_description.data(), ORBIS_NP_TROPHY_GAME_DESCR_MAX_SIZE); } } } details->group_id = groupId; data->group_id = groupId; if (node_name == "trophy") { bool current_trophy_unlockstate = node.attribute("unlockstate").as_bool(); std::string_view current_trophy_grade = node.attribute("ttype").value(); int current_trophy_group_id = node.attribute("gid").as_int(-1); if (current_trophy_grade.empty()) { continue; } if (current_trophy_group_id == groupId) { group_info.num_trophies++; int trophyGrade = GetTrophyGradeFromChar(current_trophy_grade.at(0)); group_info.num_trophies_by_rarity[trophyGrade]++; if (current_trophy_unlockstate) { group_info.unlocked_trophies++; group_info.unlocked_trophies_by_rarity[trophyGrade]++; } } } } details->num_trophies = group_info.num_trophies; details->num_platinum = group_info.num_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_PLATINUM]; details->num_gold = group_info.num_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_GOLD]; details->num_silver = group_info.num_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_SILVER]; details->num_bronze = group_info.num_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_BRONZE]; data->unlocked_trophies = group_info.unlocked_trophies; data->unlocked_platinum = group_info.unlocked_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_PLATINUM]; data->unlocked_gold = group_info.unlocked_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_GOLD]; data->unlocked_silver = group_info.unlocked_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_SILVER]; data->unlocked_bronze = group_info.unlocked_trophies_by_rarity[ORBIS_NP_TROPHY_GRADE_BRONZE]; // maybe this should be 1 instead of 100? data->progress_percentage = 100; return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyGetTrophyIcon(OrbisNpTrophyContext context, OrbisNpTrophyHandle handle, OrbisNpTrophyId trophyId, void* buffer, size_t* size) { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyGetTrophyInfo(OrbisNpTrophyContext context, OrbisNpTrophyHandle handle, OrbisNpTrophyId trophyId, OrbisNpTrophyDetails* details, OrbisNpTrophyData* data) { LOG_INFO(Lib_NpTrophy, "Getting trophy info for id {}", trophyId); if (context == ORBIS_NP_TROPHY_INVALID_CONTEXT) return ORBIS_NP_TROPHY_ERROR_INVALID_CONTEXT; if (handle == ORBIS_NP_TROPHY_INVALID_HANDLE) return ORBIS_NP_TROPHY_ERROR_INVALID_HANDLE; if (trophyId >= 127) return ORBIS_NP_TROPHY_ERROR_INVALID_TROPHY_ID; if (details == nullptr || data == nullptr) return ORBIS_NP_TROPHY_ERROR_INVALID_ARGUMENT; if (details->size != 0x498 || data->size != 0x18) return ORBIS_NP_TROPHY_ERROR_INVALID_ARGUMENT; const auto trophy_dir = Common::FS::GetUserPath(Common::FS::PathType::MetaDataDir) / game_serial / "TrophyFiles"; auto trophy_file = trophy_dir / "trophy00" / "Xml" / "TROP.XML"; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(trophy_file.native().c_str()); if (!result) { LOG_ERROR(Lib_NpTrophy, "Failed to open trophy xml : {}", result.description()); return ORBIS_OK; } auto trophyconf = doc.child("trophyconf"); for (const pugi::xml_node& node : trophyconf.children()) { std::string_view node_name = node.name(); if (node_name == "trophy") { int current_trophy_id = node.attribute("id").as_int(ORBIS_NP_TROPHY_INVALID_TROPHY_ID); if (current_trophy_id == trophyId) { bool current_trophy_unlockstate = node.attribute("unlockstate").as_bool(); std::string_view current_trophy_grade = node.attribute("ttype").value(); std::string_view current_trophy_name = node.child("name").text().as_string(); std::string_view current_trophy_description = node.child("detail").text().as_string(); uint64_t current_trophy_timestamp = node.attribute("timestamp").as_ullong(); int current_trophy_groupid = node.attribute("gid").as_int(-1); bool current_trophy_hidden = node.attribute("hidden").as_bool(); details->trophy_id = trophyId; details->trophy_grade = GetTrophyGradeFromChar(current_trophy_grade.at(0)); details->group_id = current_trophy_groupid; details->hidden = current_trophy_hidden; strncpy(details->name, current_trophy_name.data(), ORBIS_NP_TROPHY_NAME_MAX_SIZE); strncpy(details->description, current_trophy_description.data(), ORBIS_NP_TROPHY_DESCR_MAX_SIZE); data->trophy_id = trophyId; data->unlocked = current_trophy_unlockstate; data->timestamp.tick = current_trophy_timestamp; } } } return ORBIS_OK; } s32 PS4_SYSV_ABI sceNpTrophyGetTrophyUnlockState(OrbisNpTrophyContext context, OrbisNpTrophyHandle handle, OrbisNpTrophyFlagArray* flags, u32* count) { LOG_INFO(Lib_NpTrophy, "GetTrophyUnlockState called"); if (context == ORBIS_NP_TROPHY_INVALID_CONTEXT) return ORBIS_NP_TROPHY_ERROR_INVALID_CONTEXT; if (handle == ORBIS_NP_TROPHY_INVALID_HANDLE) return ORBIS_NP_TROPHY_ERROR_INVALID_HANDLE; if (flags == nullptr || count == nullptr) return ORBIS_NP_TROPHY_ERROR_INVALID_ARGUMENT; ORBIS_NP_TROPHY_FLAG_ZERO(flags); const auto trophy_dir = Common::FS::GetUserPath(Common::FS::PathType::MetaDataDir) / game_serial / "TrophyFiles"; auto trophy_file = trophy_dir / "trophy00" / "Xml" / "TROP.XML"; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(trophy_file.native().c_str()); if (!result) { LOG_ERROR(Lib_NpTrophy, "Failed to open trophy xml : {}", result.description()); return -1; } int num_trophies = 0; auto trophyconf = doc.child("trophyconf"); for (const pugi::xml_node& node : trophyconf.children()) { std::string_view node_name = node.name(); int current_trophy_id = node.attribute("id").as_int(ORBIS_NP_TROPHY_INVALID_TROPHY_ID); bool current_trophy_unlockstate = node.attribute("unlockstate").as_bool(); if (node_name == "trophy") { num_trophies++; } if (current_trophy_unlockstate) { ORBIS_NP_TROPHY_FLAG_SET(current_trophy_id, flags); } } *count = num_trophies; return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyGroupArrayGetNum() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyIntAbortHandle() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyIntCheckNetSyncTitles() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyIntCreateHandle() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyIntDestroyHandle() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyIntGetLocalTrophySummary() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyIntGetProgress() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyIntGetRunningTitle() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyIntGetRunningTitles() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyIntGetTrpIconByUri() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyIntNetSyncTitle() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyIntNetSyncTitles() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyNumInfoGetTotal() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyRegisterContext(OrbisNpTrophyContext context, OrbisNpTrophyHandle handle, uint64_t options) { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); if (context == ORBIS_NP_TROPHY_INVALID_CONTEXT) return ORBIS_NP_TROPHY_ERROR_INVALID_CONTEXT; if (handle == ORBIS_NP_TROPHY_INVALID_HANDLE) return ORBIS_NP_TROPHY_ERROR_INVALID_HANDLE; return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySetInfoGetTrophyFlagArray() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySetInfoGetTrophyNum() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyShowTrophyList(OrbisNpTrophyContext context, OrbisNpTrophyHandle handle) { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemAbortHandle() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemBuildGroupIconUri() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemBuildNetTrophyIconUri() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemBuildTitleIconUri() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemBuildTrophyIconUri() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemCheckNetSyncTitles() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemCheckRecoveryRequired() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemCloseStorage() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemCreateContext() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemCreateHandle() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemDbgCtl() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemDebugLockTrophy() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemDebugUnlockTrophy() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemDestroyContext() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemDestroyHandle() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemDestroyTrophyConfig() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetDbgParam() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetDbgParamInt() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetGroupIcon() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetLocalTrophySummary() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetNextTitleFileEntryStatus() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetProgress() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetTitleFileStatus() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetTitleIcon() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetTitleSyncStatus() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetTrophyConfig() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetTrophyData() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetTrophyGroupData() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetTrophyIcon() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetTrophyTitleData() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetTrophyTitleIds() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetUserFileInfo() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemGetUserFileStatus() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemIsServerAvailable() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemNetSyncTitle() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemNetSyncTitles() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemOpenStorage() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemPerformRecovery() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemRemoveAll() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemRemoveTitleData() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemRemoveUserData() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemSetDbgParam() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophySystemSetDbgParamInt() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceNpTrophyUnlockTrophy(OrbisNpTrophyContext context, OrbisNpTrophyHandle handle, OrbisNpTrophyId trophyId, OrbisNpTrophyId* platinumId) { LOG_INFO(Lib_NpTrophy, "Unlocking trophy id {}", trophyId); if (context == ORBIS_NP_TROPHY_INVALID_CONTEXT) return ORBIS_NP_TROPHY_ERROR_INVALID_CONTEXT; if (handle == ORBIS_NP_TROPHY_INVALID_HANDLE) return ORBIS_NP_TROPHY_ERROR_INVALID_HANDLE; if (trophyId >= 127) return ORBIS_NP_TROPHY_ERROR_INVALID_TROPHY_ID; if (platinumId == nullptr) return ORBIS_NP_TROPHY_ERROR_INVALID_ARGUMENT; const auto trophy_dir = Common::FS::GetUserPath(Common::FS::PathType::MetaDataDir) / game_serial / "TrophyFiles"; auto trophy_file = trophy_dir / "trophy00" / "Xml" / "TROP.XML"; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(trophy_file.native().c_str()); if (!result) { LOG_ERROR(Lib_NpTrophy, "Failed to parse trophy xml : {}", result.description()); return ORBIS_OK; } *platinumId = ORBIS_NP_TROPHY_INVALID_TROPHY_ID; int num_trophies = 0; int num_trophies_unlocked = 0; pugi::xml_node platinum_node; auto trophyconf = doc.child("trophyconf"); for (pugi::xml_node& node : trophyconf.children()) { int current_trophy_id = node.attribute("id").as_int(ORBIS_NP_TROPHY_INVALID_TROPHY_ID); bool current_trophy_unlockstate = node.attribute("unlockstate").as_bool(); const char* current_trophy_name = node.child("name").text().as_string(); std::string_view current_trophy_description = node.child("detail").text().as_string(); std::string_view current_trophy_type = node.attribute("ttype").value(); if (current_trophy_type == "P") { platinum_node = node; if (trophyId == current_trophy_id) { return ORBIS_NP_TROPHY_ERROR_PLATINUM_CANNOT_UNLOCK; } } if (std::string_view(node.name()) == "trophy") { if (node.attribute("pid").as_int(-1) != ORBIS_NP_TROPHY_INVALID_TROPHY_ID) { num_trophies++; if (current_trophy_unlockstate) { num_trophies_unlocked++; } } if (current_trophy_id == trophyId) { if (current_trophy_unlockstate) { LOG_INFO(Lib_NpTrophy, "Trophy already unlocked"); return ORBIS_NP_TROPHY_ERROR_TROPHY_ALREADY_UNLOCKED; } else { if (node.attribute("unlockstate").empty()) { node.append_attribute("unlockstate") = "true"; } else { node.attribute("unlockstate").set_value("true"); } Rtc::OrbisRtcTick trophyTimestamp; Rtc::sceRtcGetCurrentTick(&trophyTimestamp); if (node.attribute("timestamp").empty()) { node.append_attribute("timestamp") = std::to_string(trophyTimestamp.tick).c_str(); } else { node.attribute("timestamp") .set_value(std::to_string(trophyTimestamp.tick).c_str()); } std::string trophy_icon_file = "TROP"; trophy_icon_file.append(node.attribute("id").value()); trophy_icon_file.append(".PNG"); std::filesystem::path current_icon_path = trophy_dir / "trophy00" / "Icons" / trophy_icon_file; AddTrophyToQueue(current_icon_path, current_trophy_name); } } } } if (!platinum_node.attribute("unlockstate").as_bool()) { if ((num_trophies - 1) == num_trophies_unlocked) { if (platinum_node.attribute("unlockstate").empty()) { platinum_node.append_attribute("unlockstate") = "true"; } else { platinum_node.attribute("unlockstate").set_value("true"); } Rtc::OrbisRtcTick trophyTimestamp; Rtc::sceRtcGetCurrentTick(&trophyTimestamp); if (platinum_node.attribute("timestamp").empty()) { platinum_node.append_attribute("timestamp") = std::to_string(trophyTimestamp.tick).c_str(); } else { platinum_node.attribute("timestamp") .set_value(std::to_string(trophyTimestamp.tick).c_str()); } int platinum_trophy_id = platinum_node.attribute("id").as_int(ORBIS_NP_TROPHY_INVALID_TROPHY_ID); const char* platinum_trophy_name = platinum_node.child("name").text().as_string(); std::string platinum_icon_file = "TROP"; platinum_icon_file.append(platinum_node.attribute("id").value()); platinum_icon_file.append(".PNG"); std::filesystem::path platinum_icon_path = trophy_dir / "trophy00" / "Icons" / platinum_icon_file; *platinumId = platinum_trophy_id; AddTrophyToQueue(platinum_icon_path, platinum_trophy_name); } } doc.save_file((trophy_dir / "trophy00" / "Xml" / "TROP.XML").native().c_str()); return ORBIS_OK; } int PS4_SYSV_ABI Func_149656DA81D41C59() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_9F80071876FFA5F6() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_F8EF6F5350A91990() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_FA7A2DD770447552() { LOG_ERROR(Lib_NpTrophy, "(STUBBED) called"); return ORBIS_OK; } void RegisterlibSceNpTrophy(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("aTnHs7W-9Uk", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyAbortHandle); LIB_FUNCTION("cqGkYAN-gRw", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyCaptureScreenshot); LIB_FUNCTION("lhE4XS9OJXs", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyConfigGetTrophyDetails); LIB_FUNCTION("qJ3IvrOoXg0", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyConfigGetTrophyFlagArray); LIB_FUNCTION("zDjF2G+6tI0", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyConfigGetTrophyGroupArray); LIB_FUNCTION("7Kh86vJqtxw", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyConfigGetTrophyGroupDetails); LIB_FUNCTION("ndLeNWExeZE", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyConfigGetTrophySetInfo); LIB_FUNCTION("6EOfS5SDgoo", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyConfigGetTrophySetInfoInGroup); LIB_FUNCTION("MW5ygoZqEBs", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyConfigGetTrophySetVersion); LIB_FUNCTION("3tWKpNKn5+I", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyConfigGetTrophyTitleDetails); LIB_FUNCTION("iqYfxC12sak", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyConfigHasGroupFeature); LIB_FUNCTION("XbkjbobZlCY", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyCreateContext); LIB_FUNCTION("q7U6tEAQf7c", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyCreateHandle); LIB_FUNCTION("E1Wrwd07Lr8", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyDestroyContext); LIB_FUNCTION("GNcF4oidY0Y", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyDestroyHandle); LIB_FUNCTION("HLwz1fRIycA", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyGetGameIcon); LIB_FUNCTION("YYP3f2W09og", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyGetGameInfo); LIB_FUNCTION("w4uMPmErD4I", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyGetGroupIcon); LIB_FUNCTION("wTUwGfspKic", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyGetGroupInfo); LIB_FUNCTION("eBL+l6HG9xk", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyGetTrophyIcon); LIB_FUNCTION("qqUVGDgQBm0", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyGetTrophyInfo); LIB_FUNCTION("LHuSmO3SLd8", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyGetTrophyUnlockState); LIB_FUNCTION("Ht6MNTl-je4", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyGroupArrayGetNum); LIB_FUNCTION("u9plkqa2e0k", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyIntAbortHandle); LIB_FUNCTION("pE5yhroy9m0", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyIntCheckNetSyncTitles); LIB_FUNCTION("edPIOFpEAvU", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyIntCreateHandle); LIB_FUNCTION("DSh3EXpqAQ4", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyIntDestroyHandle); LIB_FUNCTION("sng98qULzPA", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyIntGetLocalTrophySummary); LIB_FUNCTION("t3CQzag7-zs", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyIntGetProgress); LIB_FUNCTION("jF-mCgGuvbQ", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyIntGetRunningTitle); LIB_FUNCTION("PeAyBjC5kp8", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyIntGetRunningTitles); LIB_FUNCTION("PEo09Dkqv0o", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyIntGetTrpIconByUri); LIB_FUNCTION("kF9zjnlAzIA", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyIntNetSyncTitle); LIB_FUNCTION("UXiyfabxFNQ", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyIntNetSyncTitles); LIB_FUNCTION("hvdThnVvwdY", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyNumInfoGetTotal); LIB_FUNCTION("TJCAxto9SEU", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyRegisterContext); LIB_FUNCTION("ITUmvpBPaG0", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySetInfoGetTrophyFlagArray); LIB_FUNCTION("BSoSgiMVHnY", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySetInfoGetTrophyNum); LIB_FUNCTION("d9jpdPz5f-8", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyShowTrophyList); LIB_FUNCTION("JzJdh-JLtu0", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemAbortHandle); LIB_FUNCTION("z8RCP536GOM", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemBuildGroupIconUri); LIB_FUNCTION("Rd2FBOQE094", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemBuildNetTrophyIconUri); LIB_FUNCTION("Q182x0rT75I", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemBuildTitleIconUri); LIB_FUNCTION("lGnm5Kg-zpA", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemBuildTrophyIconUri); LIB_FUNCTION("20wAMbXP-u0", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemCheckNetSyncTitles); LIB_FUNCTION("sKGFFY59ksY", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemCheckRecoveryRequired); LIB_FUNCTION("JMSapEtDH9Q", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemCloseStorage); LIB_FUNCTION("dk27olS4CEE", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemCreateContext); LIB_FUNCTION("cBzXEdzVzvs", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemCreateHandle); LIB_FUNCTION("8aLlLHKP+No", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemDbgCtl); LIB_FUNCTION("NobVwD8qcQY", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemDebugLockTrophy); LIB_FUNCTION("yXJlgXljItk", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemDebugUnlockTrophy); LIB_FUNCTION("U0TOSinfuvw", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemDestroyContext); LIB_FUNCTION("-LC9hudmD+Y", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemDestroyHandle); LIB_FUNCTION("q6eAMucXIEM", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemDestroyTrophyConfig); LIB_FUNCTION("WdCUUJLQodM", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetDbgParam); LIB_FUNCTION("4QYFwC7tn4U", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetDbgParamInt); LIB_FUNCTION("OcllHFFcQkI", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetGroupIcon); LIB_FUNCTION("tQ3tXfVZreU", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetLocalTrophySummary); LIB_FUNCTION("g0dxBNTspC0", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetNextTitleFileEntryStatus); LIB_FUNCTION("sJSDnJRJHhI", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetProgress); LIB_FUNCTION("X47s4AamPGg", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetTitleFileStatus); LIB_FUNCTION("7WPj4KCF3D8", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetTitleIcon); LIB_FUNCTION("pzL+aAk0tQA", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetTitleSyncStatus); LIB_FUNCTION("Ro4sI9xgYl4", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetTrophyConfig); LIB_FUNCTION("7+OR1TU5QOA", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetTrophyData); LIB_FUNCTION("aXhvf2OmbiE", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetTrophyGroupData); LIB_FUNCTION("Rkt0bVyaa4Y", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetTrophyIcon); LIB_FUNCTION("nXr5Rho8Bqk", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetTrophyTitleData); LIB_FUNCTION("eV1rtLr+eys", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetTrophyTitleIds); LIB_FUNCTION("SsGLKTfWfm0", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetUserFileInfo); LIB_FUNCTION("XqLLsvl48kA", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemGetUserFileStatus); LIB_FUNCTION("-qjm2fFE64M", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemIsServerAvailable); LIB_FUNCTION("50BvYYzPTsY", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemNetSyncTitle); LIB_FUNCTION("yDJ-r-8f4S4", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemNetSyncTitles); LIB_FUNCTION("mWtsnHY8JZg", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemOpenStorage); LIB_FUNCTION("tAxnXpzDgFw", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemPerformRecovery); LIB_FUNCTION("tV18n8OcheI", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemRemoveAll); LIB_FUNCTION("kV4DP0OTMNo", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemRemoveTitleData); LIB_FUNCTION("lZSZoN8BstI", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemRemoveUserData); LIB_FUNCTION("nytN-3-pdvI", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemSetDbgParam); LIB_FUNCTION("JsRnDKRzvRw", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophySystemSetDbgParamInt); LIB_FUNCTION("28xmRUFao68", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, sceNpTrophyUnlockTrophy); LIB_FUNCTION("FJZW2oHUHFk", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, Func_149656DA81D41C59); LIB_FUNCTION("n4AHGHb-pfY", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, Func_9F80071876FFA5F6); LIB_FUNCTION("+O9vU1CpGZA", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, Func_F8EF6F5350A91990); LIB_FUNCTION("+not13BEdVI", "libSceNpTrophy", 1, "libSceNpTrophy", 1, 1, Func_FA7A2DD770447552); }; } // namespace Libraries::NpTrophy
44,811
C++
.cpp
966
38.301242
100
0.659653
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,570
driver.cpp
shadps4-emu_shadPS4/src/core/libraries/videoout/driver.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include <imgui.h> #include <pthread.h> #include "common/assert.h" #include "common/config.h" #include "common/debug.h" #include "common/thread.h" #include "core/debug_state.h" #include "core/libraries/error_codes.h" #include "core/libraries/kernel/time_management.h" #include "core/libraries/videoout/driver.h" #include "core/platform.h" #include "video_core/renderer_vulkan/renderer_vulkan.h" extern std::unique_ptr<Vulkan::RendererVulkan> renderer; extern std::unique_ptr<AmdGpu::Liverpool> liverpool; namespace Libraries::VideoOut { constexpr static bool Is32BppPixelFormat(PixelFormat format) { switch (format) { case PixelFormat::A8R8G8B8Srgb: case PixelFormat::A8B8G8R8Srgb: case PixelFormat::A2R10G10B10: case PixelFormat::A2R10G10B10Srgb: case PixelFormat::A2R10G10B10Bt2020Pq: return true; default: return false; } } constexpr u32 PixelFormatBpp(PixelFormat pixel_format) { switch (pixel_format) { case PixelFormat::A16R16G16B16Float: return 8; default: return 4; } } VideoOutDriver::VideoOutDriver(u32 width, u32 height) { main_port.resolution.fullWidth = width; main_port.resolution.fullHeight = height; main_port.resolution.paneWidth = width; main_port.resolution.paneHeight = height; present_thread = std::jthread([&](std::stop_token token) { PresentThread(token); }); } VideoOutDriver::~VideoOutDriver() = default; int VideoOutDriver::Open(const ServiceThreadParams* params) { if (main_port.is_open) { return ORBIS_VIDEO_OUT_ERROR_RESOURCE_BUSY; } main_port.is_open = true; liverpool->SetVoPort(&main_port); return 1; } void VideoOutDriver::Close(s32 handle) { std::scoped_lock lock{mutex}; main_port.is_open = false; main_port.flip_rate = 0; ASSERT(main_port.flip_events.empty()); } VideoOutPort* VideoOutDriver::GetPort(int handle) { if (handle != 1) [[unlikely]] { return nullptr; } return &main_port; } int VideoOutDriver::RegisterBuffers(VideoOutPort* port, s32 startIndex, void* const* addresses, s32 bufferNum, const BufferAttribute* attribute) { const s32 group_index = port->FindFreeGroup(); if (group_index >= MaxDisplayBufferGroups) { return ORBIS_VIDEO_OUT_ERROR_NO_EMPTY_SLOT; } if (startIndex + bufferNum > MaxDisplayBuffers || startIndex > MaxDisplayBuffers || bufferNum > MaxDisplayBuffers) { LOG_ERROR(Lib_VideoOut, "Attempted to register too many buffers startIndex = {}, bufferNum = {}", startIndex, bufferNum); return ORBIS_VIDEO_OUT_ERROR_INVALID_VALUE; } const s32 end_index = startIndex + bufferNum; if (bufferNum > 0 && std::any_of(port->buffer_slots.begin() + startIndex, port->buffer_slots.begin() + end_index, [](auto& buffer) { return buffer.group_index != -1; })) { return ORBIS_VIDEO_OUT_ERROR_SLOT_OCCUPIED; } if (attribute->reserved0 != 0 || attribute->reserved1 != 0) { LOG_ERROR(Lib_VideoOut, "Invalid reserved members"); return ORBIS_VIDEO_OUT_ERROR_INVALID_VALUE; } if (attribute->aspect_ratio != 0) { LOG_ERROR(Lib_VideoOut, "Invalid aspect ratio = {}", attribute->aspect_ratio); return ORBIS_VIDEO_OUT_ERROR_INVALID_ASPECT_RATIO; } if (attribute->width > attribute->pitch_in_pixel) { LOG_ERROR(Lib_VideoOut, "Buffer width {} is larger than pitch {}", attribute->width, attribute->pitch_in_pixel); return ORBIS_VIDEO_OUT_ERROR_INVALID_PITCH; } if (attribute->tiling_mode < TilingMode::Tile || attribute->tiling_mode > TilingMode::Linear) { LOG_ERROR(Lib_VideoOut, "Invalid tilingMode = {}", static_cast<u32>(attribute->tiling_mode)); return ORBIS_VIDEO_OUT_ERROR_INVALID_TILING_MODE; } LOG_INFO(Lib_VideoOut, "startIndex = {}, bufferNum = {}, pixelFormat = {}, aspectRatio = {}, " "tilingMode = {}, width = {}, height = {}, pitchInPixel = {}, option = {:#x}", startIndex, bufferNum, GetPixelFormatString(attribute->pixel_format), attribute->aspect_ratio, static_cast<u32>(attribute->tiling_mode), attribute->width, attribute->height, attribute->pitch_in_pixel, attribute->option); auto& group = port->groups[group_index]; std::memcpy(&group.attrib, attribute, sizeof(BufferAttribute)); group.is_occupied = true; for (u32 i = 0; i < bufferNum; i++) { const uintptr_t address = reinterpret_cast<uintptr_t>(addresses[i]); port->buffer_slots[startIndex + i] = VideoOutBuffer{ .group_index = group_index, .address_left = address, .address_right = 0, }; renderer->RegisterVideoOutSurface(group, address); LOG_INFO(Lib_VideoOut, "buffers[{}] = {:#x}", i + startIndex, address); } return group_index; } int VideoOutDriver::UnregisterBuffers(VideoOutPort* port, s32 attributeIndex) { if (attributeIndex >= MaxDisplayBufferGroups || !port->groups[attributeIndex].is_occupied) { LOG_ERROR(Lib_VideoOut, "Invalid attribute index {}", attributeIndex); return ORBIS_VIDEO_OUT_ERROR_INVALID_VALUE; } auto& group = port->groups[attributeIndex]; group.is_occupied = false; for (auto& buffer : port->buffer_slots) { if (buffer.group_index != attributeIndex) { continue; } buffer.group_index = -1; } return ORBIS_OK; } void VideoOutDriver::Flip(const Request& req) { // Whatever the game is rendering show splash if it is active if (!renderer->ShowSplash(req.frame)) { // Present the frame. renderer->Present(req.frame); } // Update flip status. auto* port = req.port; { std::unique_lock lock{port->port_mutex}; auto& flip_status = port->flip_status; flip_status.count++; flip_status.processTime = Libraries::Kernel::sceKernelGetProcessTime(); flip_status.tsc = Libraries::Kernel::sceKernelReadTsc(); flip_status.flipArg = req.flip_arg; flip_status.currentBuffer = req.index; if (req.eop) { --flip_status.gcQueueNum; } --flip_status.flipPendingNum; } // Trigger flip events for the port. for (auto& event : port->flip_events) { if (event != nullptr) { event->TriggerEvent(SCE_VIDEO_OUT_EVENT_FLIP, Kernel::SceKernelEvent::Filter::VideoOut, reinterpret_cast<void*>(req.flip_arg)); } } // Reset flip label if (req.index != -1) { port->buffer_labels[req.index] = 0; port->SignalVoLabel(); } } void VideoOutDriver::DrawBlankFrame() { const auto empty_frame = renderer->PrepareBlankFrame(false); renderer->Present(empty_frame); } bool VideoOutDriver::SubmitFlip(VideoOutPort* port, s32 index, s64 flip_arg, bool is_eop /*= false*/) { { std::unique_lock lock{port->port_mutex}; if (index != -1 && port->flip_status.flipPendingNum >= port->NumRegisteredBuffers()) { LOG_ERROR(Lib_VideoOut, "Flip queue is full"); return false; } if (is_eop) { ++port->flip_status.gcQueueNum; } ++port->flip_status.flipPendingNum; // integral GPU and CPU pending flips counter port->flip_status.submitTsc = Libraries::Kernel::sceKernelReadTsc(); } if (!is_eop) { // Before processing the flip we need to ask GPU thread to flush command list as at this // point VO surface is ready to be presented, and we will need have an actual state of // Vulkan image at the time of frame presentation. liverpool->SendCommand([=, this]() { renderer->FlushDraw(); SubmitFlipInternal(port, index, flip_arg, is_eop); }); } else { SubmitFlipInternal(port, index, flip_arg, is_eop); } return true; } void VideoOutDriver::SubmitFlipInternal(VideoOutPort* port, s32 index, s64 flip_arg, bool is_eop /*= false*/) { Vulkan::Frame* frame; if (index == -1) { frame = renderer->PrepareBlankFrame(is_eop); } else { const auto& buffer = port->buffer_slots[index]; const auto& group = port->groups[buffer.group_index]; frame = renderer->PrepareFrame(group, buffer.address_left, is_eop); } std::scoped_lock lock{mutex}; requests.push({ .frame = frame, .port = port, .flip_arg = flip_arg, .index = index, .eop = is_eop, }); } void VideoOutDriver::PresentThread(std::stop_token token) { static constexpr std::chrono::nanoseconds VblankPeriod{16666667}; const auto vblank_period = VblankPeriod / Config::vblankDiv(); Common::SetCurrentThreadName("shadPS4:PresentThread"); Common::SetCurrentThreadRealtime(vblank_period); Common::AccurateTimer timer{vblank_period}; const auto receive_request = [this] -> Request { std::scoped_lock lk{mutex}; if (!requests.empty()) { const auto request = requests.front(); requests.pop(); return request; } return {}; }; auto delay = std::chrono::microseconds{0}; while (!token.stop_requested()) { timer.Start(); // Check if it's time to take a request. auto& vblank_status = main_port.vblank_status; if (vblank_status.count % (main_port.flip_rate + 1) == 0) { const auto request = receive_request(); if (!request) { if (!main_port.is_open || DebugState.IsGuestThreadsPaused()) { DrawBlankFrame(); } } else { Flip(request); FRAME_END; } } { // Needs lock here as can be concurrently read by `sceVideoOutGetVblankStatus` std::unique_lock lock{main_port.vo_mutex}; vblank_status.count++; vblank_status.processTime = Libraries::Kernel::sceKernelGetProcessTime(); vblank_status.tsc = Libraries::Kernel::sceKernelReadTsc(); main_port.vblank_cv.notify_all(); } // Trigger flip events for the port. for (auto& event : main_port.vblank_events) { if (event != nullptr) { event->TriggerEvent(SCE_VIDEO_OUT_EVENT_VBLANK, Kernel::SceKernelEvent::Filter::VideoOut, nullptr); } } timer.End(); } } } // namespace Libraries::VideoOut
10,885
C++
.cpp
272
32.231618
100
0.631011
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,571
video_out.cpp
shadps4-emu_shadPS4/src/core/libraries/videoout/video_out.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "common/assert.h" #include "common/config.h" #include "common/logging/log.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" #include "core/libraries/system/userservice.h" #include "core/libraries/videoout/driver.h" #include "core/libraries/videoout/video_out.h" #include "core/loader/symbols_resolver.h" #include "core/platform.h" namespace Libraries::VideoOut { static std::unique_ptr<VideoOutDriver> driver; void PS4_SYSV_ABI sceVideoOutSetBufferAttribute(BufferAttribute* attribute, PixelFormat pixelFormat, u32 tilingMode, u32 aspectRatio, u32 width, u32 height, u32 pitchInPixel) { LOG_INFO(Lib_VideoOut, "pixelFormat = {}, tilingMode = {}, aspectRatio = {}, width = {}, height = {}, " "pitchInPixel = {}", GetPixelFormatString(pixelFormat), tilingMode, aspectRatio, width, height, pitchInPixel); std::memset(attribute, 0, sizeof(BufferAttribute)); attribute->pixel_format = static_cast<PixelFormat>(pixelFormat); attribute->tiling_mode = static_cast<TilingMode>(tilingMode); attribute->aspect_ratio = aspectRatio; attribute->width = width; attribute->height = height; attribute->pitch_in_pixel = pitchInPixel; attribute->option = SCE_VIDEO_OUT_BUFFER_ATTRIBUTE_OPTION_NONE; } s32 PS4_SYSV_ABI sceVideoOutAddFlipEvent(Kernel::SceKernelEqueue eq, s32 handle, void* udata) { LOG_INFO(Lib_VideoOut, "handle = {}", handle); auto* port = driver->GetPort(handle); if (port == nullptr) { return ORBIS_VIDEO_OUT_ERROR_INVALID_HANDLE; } if (eq == nullptr) { return ORBIS_VIDEO_OUT_ERROR_INVALID_EVENT_QUEUE; } Kernel::EqueueEvent event{}; event.event.ident = SCE_VIDEO_OUT_EVENT_FLIP; event.event.filter = Kernel::SceKernelEvent::Filter::VideoOut; // The library only sets EV_ADD but kernel driver forces EV_CLEAR event.event.flags = Kernel::SceKernelEvent::Flags::Clear; event.event.udata = udata; event.event.fflags = 0; event.event.data = 0; event.data = port; eq->AddEvent(event); port->flip_events.push_back(eq); return ORBIS_OK; } s32 PS4_SYSV_ABI sceVideoOutAddVblankEvent(Kernel::SceKernelEqueue eq, s32 handle, void* udata) { LOG_INFO(Lib_VideoOut, "handle = {}", handle); auto* port = driver->GetPort(handle); if (port == nullptr) { return ORBIS_VIDEO_OUT_ERROR_INVALID_HANDLE; } if (eq == nullptr) { return ORBIS_VIDEO_OUT_ERROR_INVALID_EVENT_QUEUE; } Kernel::EqueueEvent event{}; event.event.ident = SCE_VIDEO_OUT_EVENT_VBLANK; event.event.filter = Kernel::SceKernelEvent::Filter::VideoOut; // The library only sets EV_ADD but kernel driver forces EV_CLEAR event.event.flags = Kernel::SceKernelEvent::Flags::Clear; event.event.udata = udata; event.event.fflags = 0; event.event.data = 0; event.data = port; eq->AddEvent(event); port->vblank_events.push_back(eq); return ORBIS_OK; } s32 PS4_SYSV_ABI sceVideoOutRegisterBuffers(s32 handle, s32 startIndex, void* const* addresses, s32 bufferNum, const BufferAttribute* attribute) { if (!addresses || !attribute) { LOG_ERROR(Lib_VideoOut, "Addresses are null"); return ORBIS_VIDEO_OUT_ERROR_INVALID_ADDRESS; } auto* port = driver->GetPort(handle); if (!port || !port->is_open) { LOG_ERROR(Lib_VideoOut, "Invalid handle = {}", handle); return ORBIS_VIDEO_OUT_ERROR_INVALID_HANDLE; } return driver->RegisterBuffers(port, startIndex, addresses, bufferNum, attribute); } s32 PS4_SYSV_ABI sceVideoOutSetFlipRate(s32 handle, s32 rate) { LOG_TRACE(Lib_VideoOut, "called"); driver->GetPort(handle)->flip_rate = rate; return ORBIS_OK; } s32 PS4_SYSV_ABI sceVideoOutIsFlipPending(s32 handle) { LOG_TRACE(Lib_VideoOut, "called"); auto* port = driver->GetPort(handle); std::unique_lock lock{port->port_mutex}; s32 pending = port->flip_status.flipPendingNum; return pending; } s32 PS4_SYSV_ABI sceVideoOutSubmitFlip(s32 handle, s32 bufferIndex, s32 flipMode, s64 flipArg) { auto* port = driver->GetPort(handle); if (!port) { LOG_ERROR(Lib_VideoOut, "Invalid handle = {}", handle); return ORBIS_VIDEO_OUT_ERROR_INVALID_HANDLE; } if (flipMode != 1) { LOG_WARNING(Lib_VideoOut, "flipmode = {}", flipMode); } if (bufferIndex < -1 || bufferIndex > 15) { LOG_ERROR(Lib_VideoOut, "Invalid bufferIndex = {}", bufferIndex); return ORBIS_VIDEO_OUT_ERROR_INVALID_INDEX; } if (bufferIndex != -1 && port->buffer_slots[bufferIndex].group_index < 0) { LOG_ERROR(Lib_VideoOut, "Slot in bufferIndex = {} is not registered", bufferIndex); return ORBIS_VIDEO_OUT_ERROR_INVALID_INDEX; } LOG_DEBUG(Lib_VideoOut, "bufferIndex = {}, flipMode = {}, flipArg = {}", bufferIndex, flipMode, flipArg); if (!driver->SubmitFlip(port, bufferIndex, flipArg)) { LOG_ERROR(Lib_VideoOut, "Flip queue is full"); return ORBIS_VIDEO_OUT_ERROR_FLIP_QUEUE_FULL; } return ORBIS_OK; } int PS4_SYSV_ABI sceVideoOutGetEventId(const Kernel::SceKernelEvent* ev) { if (ev == nullptr) { return SCE_VIDEO_OUT_ERROR_INVALID_ADDRESS; } if (ev->filter != Kernel::SceKernelEvent::Filter::VideoOut) { return ORBIS_VIDEO_OUT_ERROR_INVALID_EVENT_QUEUE; } return ev->ident; } int PS4_SYSV_ABI sceVideoOutGetEventData(const Kernel::SceKernelEvent* ev, int64_t* data) { if (ev == nullptr || data == nullptr) { return SCE_VIDEO_OUT_ERROR_INVALID_ADDRESS; } if (ev->filter != Kernel::SceKernelEvent::Filter::VideoOut) { return ORBIS_VIDEO_OUT_ERROR_INVALID_EVENT_QUEUE; } *data = ev->data; return ORBIS_OK; } s32 PS4_SYSV_ABI sceVideoOutGetFlipStatus(s32 handle, FlipStatus* status) { if (!status) { LOG_ERROR(Lib_VideoOut, "Flip status is null"); return ORBIS_VIDEO_OUT_ERROR_INVALID_ADDRESS; } auto* port = driver->GetPort(handle); if (!port) { LOG_ERROR(Lib_VideoOut, "Invalid port handle = {}", handle); return ORBIS_VIDEO_OUT_ERROR_INVALID_HANDLE; } { std::unique_lock lock{port->port_mutex}; *status = port->flip_status; } LOG_TRACE(Lib_VideoOut, "count = {}, processTime = {}, tsc = {}, submitTsc = {}, flipArg = {}, gcQueueNum = " "{}, flipPendingNum = {}, currentBuffer = {}", status->count, status->processTime, status->tsc, status->submitTsc, status->flipArg, status->gcQueueNum, status->flipPendingNum, status->currentBuffer); return ORBIS_OK; } s32 PS4_SYSV_ABI sceVideoOutGetVblankStatus(int handle, SceVideoOutVblankStatus* status) { if (status == nullptr) { return SCE_VIDEO_OUT_ERROR_INVALID_ADDRESS; } auto* port = driver->GetPort(handle); if (!port) { LOG_ERROR(Lib_VideoOut, "Invalid port handle = {}", handle); return ORBIS_VIDEO_OUT_ERROR_INVALID_HANDLE; } std::unique_lock lock{port->vo_mutex}; *status = port->vblank_status; return ORBIS_OK; } s32 PS4_SYSV_ABI sceVideoOutGetResolutionStatus(s32 handle, SceVideoOutResolutionStatus* status) { LOG_INFO(Lib_VideoOut, "called"); *status = driver->GetPort(handle)->resolution; return ORBIS_OK; } s32 PS4_SYSV_ABI sceVideoOutOpen(SceUserServiceUserId userId, s32 busType, s32 index, const void* param) { LOG_INFO(Lib_VideoOut, "called"); ASSERT(busType == SCE_VIDEO_OUT_BUS_TYPE_MAIN); if (index != 0) { LOG_ERROR(Lib_VideoOut, "Index != 0"); return ORBIS_VIDEO_OUT_ERROR_INVALID_VALUE; } auto* params = reinterpret_cast<const ServiceThreadParams*>(param); int handle = driver->Open(params); if (handle < 0) { LOG_ERROR(Lib_VideoOut, "All available handles are open"); return ORBIS_VIDEO_OUT_ERROR_RESOURCE_BUSY; } return handle; } s32 PS4_SYSV_ABI sceVideoOutClose(s32 handle) { driver->Close(handle); return ORBIS_OK; } s32 PS4_SYSV_ABI sceVideoOutUnregisterBuffers(s32 handle, s32 attributeIndex) { auto* port = driver->GetPort(handle); if (!port || !port->is_open) { return ORBIS_VIDEO_OUT_ERROR_INVALID_HANDLE; } return driver->UnregisterBuffers(port, attributeIndex); } void sceVideoOutGetBufferLabelAddress(s32 handle, uintptr_t* label_addr) { auto* port = driver->GetPort(handle); ASSERT(port); *label_addr = reinterpret_cast<uintptr_t>(port->buffer_labels.data()); } s32 sceVideoOutSubmitEopFlip(s32 handle, u32 buf_id, u32 mode, u32 arg, void** unk) { auto* port = driver->GetPort(handle); if (!port) { return ORBIS_VIDEO_OUT_ERROR_INVALID_HANDLE; } Platform::IrqC::Instance()->RegisterOnce( Platform::InterruptId::GfxFlip, [=](Platform::InterruptId irq) { ASSERT_MSG(irq == Platform::InterruptId::GfxFlip, "An unexpected IRQ occured"); ASSERT_MSG(port->buffer_labels[buf_id] == 1, "Out of order flip IRQ"); const auto result = driver->SubmitFlip(port, buf_id, arg, true); ASSERT_MSG(result, "EOP flip submission failed"); }); return ORBIS_OK; } s32 PS4_SYSV_ABI sceVideoOutGetDeviceCapabilityInfo( s32 handle, SceVideoOutDeviceCapabilityInfo* pDeviceCapabilityInfo) { pDeviceCapabilityInfo->capability = 0; return ORBIS_OK; } s32 PS4_SYSV_ABI sceVideoOutWaitVblank(s32 handle) { auto* port = driver->GetPort(handle); if (!port) { return ORBIS_VIDEO_OUT_ERROR_INVALID_HANDLE; } std::unique_lock lock{port->vo_mutex}; const auto prev_counter = port->vblank_status.count; port->vblank_cv.wait(lock, [&]() { return prev_counter != port->vblank_status.count; }); return ORBIS_OK; } void RegisterLib(Core::Loader::SymbolsResolver* sym) { driver = std::make_unique<VideoOutDriver>(Config::getScreenWidth(), Config::getScreenHeight()); LIB_FUNCTION("SbU3dwp80lQ", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutGetFlipStatus); LIB_FUNCTION("U46NwOiJpys", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutSubmitFlip); LIB_FUNCTION("w3BY+tAEiQY", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutRegisterBuffers); LIB_FUNCTION("HXzjK9yI30k", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutAddFlipEvent); LIB_FUNCTION("Xru92wHJRmg", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutAddVblankEvent); LIB_FUNCTION("CBiu4mCE1DA", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutSetFlipRate); LIB_FUNCTION("i6-sR91Wt-4", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutSetBufferAttribute); LIB_FUNCTION("6kPnj51T62Y", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutGetResolutionStatus); LIB_FUNCTION("Up36PTk687E", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutOpen); LIB_FUNCTION("zgXifHT9ErY", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutIsFlipPending); LIB_FUNCTION("N5KDtkIjjJ4", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutUnregisterBuffers); LIB_FUNCTION("uquVH4-Du78", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutClose); LIB_FUNCTION("1FZBKy8HeNU", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutGetVblankStatus); LIB_FUNCTION("kGVLc3htQE8", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutGetDeviceCapabilityInfo); LIB_FUNCTION("j6RaAUlaLv0", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutWaitVblank); LIB_FUNCTION("U2JJtSqNKZI", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutGetEventId); LIB_FUNCTION("rWUTcKdkUzQ", "libSceVideoOut", 1, "libSceVideoOut", 0, 0, sceVideoOutGetEventData); // openOrbis appears to have libSceVideoOut_v1 module libSceVideoOut_v1.1 LIB_FUNCTION("Up36PTk687E", "libSceVideoOut", 1, "libSceVideoOut", 1, 1, sceVideoOutOpen); LIB_FUNCTION("CBiu4mCE1DA", "libSceVideoOut", 1, "libSceVideoOut", 1, 1, sceVideoOutSetFlipRate); LIB_FUNCTION("HXzjK9yI30k", "libSceVideoOut", 1, "libSceVideoOut", 1, 1, sceVideoOutAddFlipEvent); LIB_FUNCTION("i6-sR91Wt-4", "libSceVideoOut", 1, "libSceVideoOut", 1, 1, sceVideoOutSetBufferAttribute); LIB_FUNCTION("w3BY+tAEiQY", "libSceVideoOut", 1, "libSceVideoOut", 1, 1, sceVideoOutRegisterBuffers); LIB_FUNCTION("U46NwOiJpys", "libSceVideoOut", 1, "libSceVideoOut", 1, 1, sceVideoOutSubmitFlip); LIB_FUNCTION("SbU3dwp80lQ", "libSceVideoOut", 1, "libSceVideoOut", 1, 1, sceVideoOutGetFlipStatus); LIB_FUNCTION("kGVLc3htQE8", "libSceVideoOut", 1, "libSceVideoOut", 1, 1, sceVideoOutGetDeviceCapabilityInfo); } } // namespace Libraries::VideoOut
13,319
C++
.cpp
292
38.890411
100
0.672758
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,572
remoteplay.cpp
shadps4-emu_shadPS4/src/core/libraries/remote_play/remoteplay.cpp
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "remoteplay.h" #include "common/logging/log.h" #include "core/libraries/error_codes.h" #include "core/libraries/libs.h" namespace Libraries::Remoteplay { int PS4_SYSV_ABI sceRemoteplayApprove() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayChangeEnterKey() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayClearAllRegistData() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayClearConnectHistory() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayConfirmDeviceRegist() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayDisconnect() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayGeneratePinCode() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayGetApMode() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayGetConnectHistory() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayGetConnectionStatus(s32 userId, int* pStatus) { *pStatus = ORBIS_REMOTEPLAY_CONNECTION_STATUS_DISCONNECT; return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayGetConnectUserId() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayGetMbusDeviceInfo() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayGetOperationStatus() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayGetRemoteplayStatus() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayGetRpMode() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayImeClose() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayImeFilterResult() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayImeGetEvent() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayImeNotify() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayImeNotifyEventResult() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayImeOpen() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayImeSetCaret() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayImeSetText() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayInitialize() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayIsRemoteOskReady() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayIsRemotePlaying() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayNotifyMbusDeviceRegistComplete() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayNotifyNpPushWakeup() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayNotifyPinCodeError() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayNotifyUserDelete() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayPrintAllRegistData() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayProhibit() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayProhibitStreaming() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayServerLock() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayServerUnLock() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplaySetApMode() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplaySetLogLevel() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplaySetProhibition() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplaySetProhibitionForVsh() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplaySetRpMode() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI sceRemoteplayTerminate() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } int PS4_SYSV_ABI Func_1D5EE365ED5FADB3() { LOG_ERROR(Lib_Remoteplay, "(STUBBED) called"); return ORBIS_OK; } void RegisterlibSceRemoteplay(Core::Loader::SymbolsResolver* sym) { LIB_FUNCTION("xQeIryTX7dY", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayApprove); LIB_FUNCTION("IYZ+Mu+8tPo", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayChangeEnterKey); LIB_FUNCTION("ZYUsJtcAnqA", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayClearAllRegistData); LIB_FUNCTION("cCheyCbF7qw", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayClearConnectHistory); LIB_FUNCTION("tPYT-kGbZh8", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayConfirmDeviceRegist); LIB_FUNCTION("6Lg4BNleJWc", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayDisconnect); LIB_FUNCTION("j98LdSGy4eY", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayGeneratePinCode); LIB_FUNCTION("L+cL-M-DP3w", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayGetApMode); LIB_FUNCTION("g4K51cY+PEw", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayGetConnectHistory); LIB_FUNCTION("g3PNjYKWqnQ", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayGetConnectionStatus); LIB_FUNCTION("3eBNV9A0BUM", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayGetConnectUserId); LIB_FUNCTION("ufesWMVX6iU", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayGetMbusDeviceInfo); LIB_FUNCTION("DxU4JGh4S2k", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayGetOperationStatus); LIB_FUNCTION("n5OxFJEvPlc", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayGetRemoteplayStatus); LIB_FUNCTION("Cekhs6LSHC0", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayGetRpMode); LIB_FUNCTION("ig1ocbR7Ptw", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayImeClose); LIB_FUNCTION("gV9-8cJPM3I", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayImeFilterResult); LIB_FUNCTION("cMk57DZXe6c", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayImeGetEvent); LIB_FUNCTION("-gwkQpOCl68", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayImeNotify); LIB_FUNCTION("58v9tSlRxc8", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayImeNotifyEventResult); LIB_FUNCTION("C3r2zT5ebMg", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayImeOpen); LIB_FUNCTION("oB730zwoz0s", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayImeSetCaret); LIB_FUNCTION("rOTg1Nljp8w", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayImeSetText); LIB_FUNCTION("k1SwgkMSOM8", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayInitialize); LIB_FUNCTION("R8RZC1ZIkzU", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayIsRemoteOskReady); LIB_FUNCTION("uYhiELUtLgA", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayIsRemotePlaying); LIB_FUNCTION("d-BBSEq1nfc", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayNotifyMbusDeviceRegistComplete); LIB_FUNCTION("Yytq7NE38R8", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayNotifyNpPushWakeup); LIB_FUNCTION("Wg-w8xjMZA4", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayNotifyPinCodeError); LIB_FUNCTION("yheulqylKwI", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayNotifyUserDelete); LIB_FUNCTION("t5ZvUiZ1hpE", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayPrintAllRegistData); LIB_FUNCTION("mrNh78tBpmg", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayProhibit); LIB_FUNCTION("7QLrixwVHcU", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayProhibitStreaming); LIB_FUNCTION("-ThIlThsN80", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayServerLock); LIB_FUNCTION("0Z-Pm5rZJOI", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayServerUnLock); LIB_FUNCTION("xSrhtSLIjOc", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplaySetApMode); LIB_FUNCTION("5-2agAeaE+c", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplaySetLogLevel); LIB_FUNCTION("Rf0XMVR7xPw", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplaySetProhibition); LIB_FUNCTION("n4l3FTZtNQM", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplaySetProhibitionForVsh); LIB_FUNCTION("-BPcEQ1w8xc", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplaySetRpMode); LIB_FUNCTION("BOwybKVa3Do", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, sceRemoteplayTerminate); LIB_FUNCTION("HV7jZe1frbM", "libSceRemoteplay", 1, "libSceRemoteplay", 0, 0, Func_1D5EE365ED5FADB3); }; } // namespace Libraries::Remoteplay
11,000
C++
.cpp
262
36.160305
80
0.700524
shadps4-emu/shadPS4
9,253
501
185
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false